c++ - 如何有条件地定义默认构造函数?

标签 c++ c++11 default-constructor enable-if

我在想一个像这样的类:

template < typename ...Whatever >
class MyClass
{
public:
    static constexpr bool has_default_ctr = Something;

    // I want this only if "has_default_ctr" is "true".
    MyClass();

    //...
};

我认为我不能为此使用构造函数模板和 std::enable_if(因为没有参数)。我错了吗?如果没有,是否有其他方法可以做到这一点?

最佳答案

C++11 允许(可靠地)在模板参数中使用 enable_if 风格的 SFINAE:

template<
    // This is needed to make the condition dependent
    bool B = has_default_ctr
    , typename std::enable_if<B, int>::type = 0
>
MyClass();

// When outside of class scope:
// have to repeat the condition for out-of-line definition
template<bool B, typename std::enable_if<B, int>::type = 0>
MyClass::MyClass()
/* define here */

在 C++03 中,您可以使用带有默认参数的一元构造函数——默认参数意味着该构造函数仍算作默认构造函数。

关于c++ - 如何有条件地定义默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309529/

相关文章:

c++ - C++:在数组中输入数字时,第一个数字为0

c++ - constexpr 未定义行为

c++ - 创建非默认可构造类的虚拟对象

c++ - (C++) 使类静态 : put the constructor as private or delete it publically? 时什么更好

键和文件的 C++ 映射不起作用

c++ - 为什么 '::' 、 '.' 、 '?:' 等运算符不能在 C++ 中重载?

c++ - 在 (C++-AMP) 中处理异构 vector

c++ - 采用模板非类型模板参数的函数模板

c# - 为什么我的数组默认构造函数没有在这里被调用?

c++ - 当其他构造函数存在时,为什么 "ctor() = default"会改变行为?