模板重载和SFINAE仅适用于函数,不适用于类 [英] template overloading and SFINAE working only with functions but not classes

查看:106
本文介绍了模板重载和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).

这篇关于模板重载和SFINAE仅适用于函数,不适用于类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆