c++ - 如何根据模板类型使用 std::enable_if 来启用或禁用构造函数?

标签 c++ templates c++11

我有以下模板化对象:

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, 
           typename std::enable_if<!std::is_same<T1, 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, 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);
}

另请阅读:Select class constructor using enable_if

关于c++ - 如何根据模板类型使用 std::enable_if 来启用或禁用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26644077/

相关文章:

c++ - Qt 中的反跳事件过滤器

c++ - 如何向后读取文件以有效地查找子字符串

c++ - 将csv文件读入C++

c++ - 用于控制算法的仿函数的编译时容器?

c++ - OpenGL 应用程序在不同计算机上的工作方式不同

c++ - 模板非类型参数?

c++ - 如何使用模板生成整数序列在这里工作

c++ - 模板-无法将函数定义与现有声明c++匹配

c++ - Visual Studio 2013 C++类属性初始化问题

c++ - 如何表达转发引用的常量?