据我所知,SFINAE意味着替换失败不会导致编译错误,而只是将原型从可能的重载列表中删除。
我不明白的是:为什么这个SFINAE:
template <bool C, typename T = void> struct enable_if{};
template <typename T> struct enable_if<true, T> { typedef T type; };但这不是?
template <bool C> struct assert;
template <> struct assert<true>{};根据我的理解,这里的基本逻辑是相同的。这个问题是从this answer的评论中提出来的。
发布于 2013-07-24 09:27:22
在C++98中,SFINAE使用返回类型或函数的虚拟参数(默认参数)来完成。
// SFINAE on return type for functions with fixed arguments (e.g. operator overloading)
template<class T>
typename std::enable_if< std::is_integral<T>::value, void>::type
my_function(T const&);
// SFINAE on dummy argument with default parameter for functions with no return type (e.g. constructors)
template<class T>
void my_function(T const&, std::enable_if< std::is_integral<T>::value, void>::type* = nullptr);在这两种情况下,为了得到嵌套型的T而进行type的研究是type的本质。与std::enable_if不同的是,您的assert模板没有一个嵌套类型的,可以用于替代SFINAE的一部分。
有关更多细节,请参见Jonathan的优秀ACCU 2013 presentation,以及C++11表达式SFINAE。除其他外(正如@BartekBanachewicz在注释中指出的那样),现在也可以在函数模板默认参数中使用SFINAE。
// use C++11 default function arguments, no clutter in function's signature!
template<class T, class dummy = typename std::enable_if< std::is_integral<T>::value, void>::type>
void my_function(T const&);https://stackoverflow.com/questions/17829874
复制相似问题