我如何有条件地定义默认构造函数?

CTM*_*ser 7 c++ default-constructor enable-if c++11

我在考虑一个类:

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

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

    //...
};
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*ton 13

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 */
Run Code Online (Sandbox Code Playgroud)

在C++ 03中,你可以使用带有默认参数的一元构造函数 - 默认参数意味着构造函数仍然算作默认构造函数.


小智 -1

您可以使用具有不同参数的不同构造函数

MyClass(){

}
MyClass(int num){

}
MyClass(String s){
}
Run Code Online (Sandbox Code Playgroud)

您可以简单地编写静态函数来返回类并在其中写入条件:

static chooseContructor(/*parameters*/){
 if(/*something*/){
     return new MyCLass();
 }
 else if(/*something else*/){
     return new MyClass(int num);
 }
 else if{
    return new MyClass(String s);
 }
}
Run Code Online (Sandbox Code Playgroud)

等等...类似的东西会给你一个半自动构造函数选择器