c++ - 模板重载和 SFINAE 仅适用于函数而不适用于类

标签 c++ templates c++11 sfinae

谁能解释一下为什么编译器只接受这段代码

template<typename L, size_t offset, typename enable_if< (offset<sizeof(L)), int >::type =0>
void a_function(){}

template<typename L, size_t offset, typename enable_if< (offset==sizeof(L)), int >::type =0>
void a_function(){}

但不是这个:

template<typename L, size_t offset, typename enable_if< (offset<sizeof(L)), int >::type =0>
class a_class{};

template<typename L, size_t offset, typename enable_if< (offset==sizeof(L)), int >::type =0>
class a_class{};

编译器将第二个类模板视为对第一个类模板的重新定义。

最佳答案

您必须对类(class)使用特化。通常,它是通过一个额外的参数来完成的:

template <class P, class dummy = void>
class T;

template <class P>
class T<P, typename enable_if<something, void>::type> {
   the real thing
};

两个同名的类(或类模板)声明应该总是声明同一个类或类模板(或者是一个特化,在这种情况下它仍然是同一个模板)。

关于c++ - 模板重载和 SFINAE 仅适用于函数而不适用于类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079746/

相关文章:

c++ - 从十六进制字符数组复制到 char * 类型

c++ - 将类与运算符 [] 一起使用

c++11 - 从 vector C++ 中查找字符串中的字符/字符串

c++ - VC++错误 "no operator << matches these operands",但它可以与其他编译器一起使用

c++ - Ptr-to-member 模板参数的 Friend 语法

c++ - 自定义类中的 move 与复制性能

c++ - 如何在 Windows 8 64 位操作系统中注册 .DLL 文件?

c++ - 使用 MSVC 的模块中的访问冲突

c++ - 编译模板时出现 clang 错误

c++ - 为什么 ostream iomanip 在传递给操作符 << 时不需要模板参数?