谁能解释一下为什么编译器只接受这段代码
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/