nij*_*sen 13 c++ templates sfinae c++11 argument-deduction
据我所知,SFINAE意味着替换失败不会导致编译错误,只是从可能的重载列表中删除原型.
我不明白:为什么这个SFINAE:
template <bool C, typename T = void> struct enable_if{};
template <typename T> struct enable_if<true, T> { typedef T type; };
Run Code Online (Sandbox Code Playgroud)
但这不是吗?
template <bool C> struct assert;
template <> struct assert<true>{};
Run Code Online (Sandbox Code Playgroud)
根据我的理解,这里的基本逻辑是相同的.这个问题来自对这个答案的评论.
Tem*_*Rex 15
在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);
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,T为了获得嵌套类型type而进行的替换是SFINAE的本质.与此相反std::enable_if,您的assert模板没有可以在SFINAE的替换部分中使用的嵌套类型.
有关更多详细信息以及C++ 11表达式SFINAE,请参阅Jonathan Wakely出色的ACCU 2013演示文稿.其中(正如@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&);
Run Code Online (Sandbox Code Playgroud)