为什么 class A
编译和 class B
不编译,编译器提示有两个声明,不是都依赖 SFINAE 吗?
在使用 foo
时,两者实际上都应该使用模板类型推导吗?
所以真正的问题是,这两个版本有什么细微的不同
为什么 A 类
成功使用 sfinae...?
- A 类使用默认值(零)匿名(不必要)非类型 模板参数
- B 类使用type-defaulted(带 enable_if)annonymous type 模板参数
代码:
template<typename T>
struct A
{
template<typename U,
typename std::enable_if<!std::is_floating_point<U>::value>::type * = nullptr
>
void foo() {}
template<typename U,
typename std::enable_if<std::is_floating_point<U>::value>::type * = nullptr
>
void foo() {}
};
template<typename T>
struct B
{
template<typename U,
typename = typename std::enable_if<!std::is_floating_point<U>::value>::type
>
void foo() {}
template<typename U,
typename = typename std::enable_if<std::is_floating_point<U>::value>::type
>
void foo() {}
};
最佳答案
§1.3.22 定义函数模板的签名:
signature
<
class member function template>
name, parameter type list (8.3.5), class of which the function is a member, cv-qualifiers (if any), ref-qualifier (if any), return type, and template parameter list
模板参数列表不包括给定的默认参数。对于 A::foo
,模板参数不等效(在 §14.5.6.1 中精确定义的术语)。在 B::foo
, 他们是。您只是用不同的默认参数声明相同的函数模板——因此违反了 §9.2/1 和 §14.1/12。
当仅通过 enable_if
的条件重载函数模板时,这是一个常见问题。 .特别是对于构造函数,您不能在其中放置 enable_if
返回值中的一部分。
关于c++ - 类成员函数的 SFINAE(一个编译另一个不编译),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625914/