c++ - How do I use std::enable_if to enable or disable constructors depending on template types? -
c++ - How do I use std::enable_if to enable or disable constructors depending on template types? -
i have next templated object:
template< typename type_1, typename type_2 > struct result { // want enable these 2 constructors if type_1 != type_2 result( type_1 f ) : foo{f} {} result( type_2 b ) : bar{b} {} // want enable constructor if type_1 == type_2 result( type_1 f, type_2 b ) : foo{f}, bar{b} {} // other fellow member functions removed. type_1 foo; type_2 bar; };
how utilize std::enable_if
enable or disable constructors required?
e.g:
this 1 have first 2 constructors:
result<string,int> // type_1 != type_2
this 1 have 3rd constructor:
result<int,int> // type_1 == type_2
this seems working, not sure optimal way
so add together new template parameters default values constructor enable sfinae
#include <type_traits> template< typename type_1, typename type_2 > struct result { // want enable these 2 constructors 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, typename std::enable_if<!std::is_same<t1, t2>::value, int >::type * = nullptr ) : bar{b} {} /* ^^^ need avoid duplicated signature error above one*/ // want enable constructor if type_1 == type_2 template<typename t1 = type_1, typename t2 = type_2> result( type_1 f, 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); }
also read: select class constructor using enable_if
c++ templates c++11
Comments
Post a Comment