我有以下模板对象:
@H_404_17@解决方法
template< typename type_1,typename type_2 > struct result { // I want to enable these two constructors only if type_1 != type_2 result( type_1 f ) : foo{f} {} result( type_2 b ) : bar{b} {} // I want to enable this constructor only if type_1 == type_2 result( type_1 f,type_2 b ) : foo{f},bar{b} {} // Other member functions removed. type_1 foo; type_2 bar; };
如何根据需要使用std :: enable_if启用或禁用构造函数?
例如:
这个只有前两个构造函数:
result<string,int> // type_1 != type_2
这个只有第三个构造函数:
result<int,int> // type_1 == type_2
This似乎有效,但我不确定它是最佳方式
因此,只需将具有默认值的新模板参数添加到构造函数以启用SFINAE
#include <type_traits> template< typename type_1,typename type_2 > struct result { // I want to enable these two constructors only if type_1 != type_2 template<typename T1 = type_1,typename T2 = type_2> result( type_1 f,typename std::enable_if<!std::is_same<T1,T2>::value>::type * = nullptr ) : foo{f} {} template<typename T1 = type_1,typename T2 = type_2> result( type_2 b,T2>::value,int >::type * = nullptr ) : bar{b} {} /* ^^^ need this to avoid duplicated signature error with above one*/ // I want to enable this constructor only if type_1 == type_2 template<typename T1 = type_1,type_2 b,typename std::enable_if<std::is_same<T1,T2>::value>::type * = nullptr ) : foo{f},bar{b} {} type_1 foo; type_2 bar; }; int main() { result<int,double> r(1); result<int,double> r2(1.0); result<int,int> r3(1,2); // disbaled //result<int,double> r4(1,2.0); //result<int,int> r5(1); }