我正在写一个模板类,想知道模板参数是否是 default constructible有什么办法吗?
代码如下
template <class C>
class A
{
createObj()
{
C* objPtr = NULL;
// If default constructible then create object else let it remain NULL
}
};
更新:我试过使用 code given in this question但它不起作用,准确地说,如果返回默认可构造的,即使对于那些不是的类,我不知道为什么会这样。
最佳答案
在另一个答案中,Potatoswatter 已经发布了类型特征 is_default_constructible
可以在这里重复使用:
void createObj(
typename enable_if_c<is_default_constructible<C>::value, void>::type* dummy = 0)
{
C* objPtr = new C();
}
void createObj(
typename disable_if_c<is_default_constructible<C>::value, void>::type* dummy = 0)
{
C* objPtr = 0;
}
或者,如果您的函数具有非 void 返回类型 T
(感谢 DeadMG)你可以省略虚拟默认参数:
typename enable_if_c<is_default_constructible<C>::value, T>::type createObj()
{
C* objPtr = new C();
}
typename disable_if_c<is_default_constructible<C>::value, T>::type createObj()
{
C* objPtr = 0;
}
SFINAE 表示无法为给定类型实例化的模板将不会实例化。 enable_if_c
当且仅当其参数为 true
时,基本上会产生有效类型.现在我们使用元函数 is_default_constructible
测试类型是否为C
有一个默认的构造函数。如果是这样,enable_if_c<…>::type
将产生有效类型,否则不会。
C++ 编译器因此只会看到两个函数之一,即在您的上下文中可用的函数。请参阅 enable_if
的文档了解更多详情。
关于c++ - 如何检查模板参数是否默认可构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669131/