我在想一个像这样的类:
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/