使用尾随返回类型的条件重载可能? [英] Conditional overloading with trailing-return-type possible?
问题描述
假设您尝试执行以下操作:
Suppose you attempt to do the following:
template</* args */>
typename std::enable_if< /*conditional*/ , /*type*/ >::type
static auto hope( /*args*/) -> decltype( /*return expr*/ )
{
}
可以结合条件包含/重载( std :: enable_if
)与trailing-return-type( auto ... - > decltype / code>)?
Is it possible to combine conditional inclusion/overloading (std::enable_if
) with trailing-return-type (auto ... -> decltype()
)?
我不会在使用预处理器的解决方案有趣。我总是可以做像
I would not be interesting in solutions using the preprocessor. I can always do things like
#define RET(t) --> decltype(t) { return t; }
并扩展它以接受整个条件。相反,如果语言支持它,而不使用另一个trait为返回类型,即 ReturnType< A,B> :: type_t
或任何在函数体中使用,我感兴趣。
and extend it to take also the whole conditional. Instead I am interested if the language supports it without using another trait for the return type, i.e. ReturnType<A,B>::type_t
or whatever is used in the function body.
推荐答案
trailing-return-type 与正常的return类型它在参数列表和cv- / ref-qualifiers之后指定。此外,它不一定需要 decltype
,正常类型也很好:
The trailing-return-type isn't much different from the normal return type, except that it's specified after the parameter list and cv-/ref-qualifiers. Also, it doesn't necessarily need decltype
, a normal type is fine too:
auto answer() -> int{ return 42; }
现在你应该看到你的问题的答案是:
So by now you should see what the answer to your question is:
template<class T>
using Apply = typename T::type; // I don't like to spell this out
template</* args */>
static auto hope( /*args*/)
-> Apply<std::enable_if</* condition */, decltype( /*return expr*/ )>>
{
}
虽然我个人更喜欢使用 decltype
和表达式SFINAE,只要条件可以表达为一个表达式(例如,你可以调用某个类型的对象上的函数):
Though I personally prefer using just decltype
and expression SFINAE, as long as the condition can be expressed as an expression (e.g., can you invoke a function on an object of a certain type):
template<class T>
static auto hope(T const& arg)
-> decltype(arg.foo(), void())
{
// ...
}
这篇关于使用尾随返回类型的条件重载可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!