使用enable_if选择类构造函数 [英] Select class constructor using enable_if
问题描述
请考虑以下代码:
#include <iostream>
#include <type_traits>
template <typename T>
struct A {
int val = 0;
template <class = typename std::enable_if<T::value>::type>
A(int n) : val(n) {};
A(...) { }
/* ... */
};
struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };
int main() {
A<YES> y(10);
A<NO> n;
std::cout << "YES: " << y.val << std::endl
<< "NO: " << n.val << std::endl;
}
我想选择性地定义构造函数A :: A类型使用enable_if。对于所有其他类型,有默认构造函数A :: A(...),它应该是替换失败时编译器的默认情况。但是这对我有意义的编译器(gcc版本4.9.0 20130714)仍然抱怨
I want to selectively define constructor A::A(int) only for some types using enable_if. For all other types there is default constructor A::A(...) which should be the default case for compiler when substitution fails. However this makes sense for me compiler (gcc version 4.9.0 20130714) is still complaining
sfinae.cpp:在实例化'struct A ':sfinae.cpp:19:11:
从这里需要sfinae.cpp:9:5:错误:没有类型命名为'type'在
'struct std :: enable_if '
A(int n):val(n){};
sfinae.cpp: In instantiation of 'struct A': sfinae.cpp:19:11:
required from here sfinae.cpp:9:5: error: no type named 'type' in
'struct std::enable_if'
A(int n) : val(n) {};
这样的构造函数是否可能?这是可能与另一个构造函数(复制构造函数和移动构造函数)?
Is something like this possible for constructor? Is this possible with another constructor(s) (copy-constructor and move-constructor)?
推荐答案
使用单个默认模板参数,因为它的值需要在实例化类模板时解决。
I think this can't work with a single defaulted template parameter, because its value needs to be resolved when the class template is instantiated.
我们需要将替换推迟到构造函数模板实例化。一种方法是将模板参数默认为T,并为构造函数添加一个额外的虚拟参数:
We need to defer the substitution to the point of constructor template instantiation. One way is to default the template parameter to T and add an extra dummy parameter to the constructor:
template<typename U = T>
A(int n, typename std::enable_if<U::value>::type* = 0) : val(n) { }
这篇关于使用enable_if选择类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!