c++ - SFINAE 意想不到的结果

标签 c++ c++11 sfinae type-traits

尝试了解 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/

相关文章:

c++ - 通过将标准输入/输出重定向到管道来制作子进程

c++ - 从命令提示符执行 C++ 程序

c++ - 在 C++ 的纯静态公共(public)接口(interface)上删除复制/赋值运算符是否有意义?

c++ - std::enable_if 在模板参数上确定 STL 容器

c++ - 替代 'new'动态数组的push_back吗?

c++ - struct c++ 中的默认参数

c++ - 使用=delete 进行接口(interface)描述

c++ - 匹配成员函数存在和签名 : parameters

C++:合并排序和插入排序混合

c++ - 使用 unique_ptr 和自定义删除器包装 C 代码