尝试了解 SFINAE。
template <class T, class T1 = void>
struct foo
{
static constexpr char* a = "primary definition\n";
};
struct A
{
};
template <class T>
struct foo<T, std::enable_if<std::is_same<T, A>::value>::type>
{
static constexpr char* a = "secondary definition\n";
};
编译器gcc-4.8.1给出错误
error: type/value mismatch at argument 2 in template parameter list for ‘template struct foo’ struct foo::value>::type>
最佳答案
C++11 Standard: 14.6/3
When a qualified-id is intended to refer to a type that is not a member of the current instantiation (14.6.2.1) and its nested-name-specifier refers to a dependent type, it shall be prefixed by the keyword
typename
forming a typename-specifier.
T
是依赖类型,因此需要 typename
关键字:
struct foo<T, typename std::enable_if<std::is_same<T, A>::value>::type>
// ^^^^^^^^
C++14 中还提供了一个帮助程序模板,它是返回类型的别名:
struct foo<T, std::enable_if_t<std::is_same<T, A>::value>>
// ^^^^^^^^^^^^^^^^
关于c++ - SFINAE 意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210969/