模板重载和SFINAE仅适用于函数,不适用于类

模板重载和SFINAE仅适用于函数,不适用于类

问题描述:

有人可以解释为什么编译器只接受此代码

can someone explain why the compiler accepts only this code

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{};

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

The compiler sees the second class template as a redefinition of the first.

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

You have to use specialization for classes. Typically, it is done with an extra parameter:

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

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

两个具有相同名称的类(或类模板)声明应始终声明相同的类或类模板(或者是专业化,在这种情况下,它仍然是相同的模板)。

Two class (or class template) declarations with the same name should always declare the same class or class template (or be a specialization, in which case it is still the same template).