如何检查模板参数是否是默认可构造的

Gau*_*rav 5 c++ implementation templates

我正在编写一个模板类,并想知道模板参数是否是默认的可构造的有没有办法做到这一点?

代码类似于以下内容

template <class C>
class A
{

createObj()
{
C* objPtr = NULL;
// If default constructible then create object else let it remain NULL
}
};
Run Code Online (Sandbox Code Playgroud)

更新:我已尝试使用此问题中给出的代码,但它不起作用,确切地说,如果返回默认可构造甚至对于那些不是的类,我不知道为什么会发生这种情况.

Kon*_*lph 3

这是SFINAE和的经典案例enable_if

\n\n

在另一个答案中,Potatoswatter 已经发布了一个is_default_constructible可以在此处重用的类型特征:

\n\n
void createObj(\n    typename enable_if_c<is_default_constructible<C>::value, void>::type* dummy = 0)\n{\n     C* objPtr = new C();\n}\n\nvoid createObj(\n    typename disable_if_c<is_default_constructible<C>::value, void>::type* dummy = 0)\n{\n     C* objPtr = 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,如果您的函数具有非 void 返回类型T(感谢 DeadMG),您可以省略虚拟默认参数:

\n\n
typename enable_if_c<is_default_constructible<C>::value, T>::type createObj()\n{\n     C* objPtr = new C();\n}\n\ntypename disable_if_c<is_default_constructible<C>::value, T>::type createObj()\n{\n     C* objPtr = 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

SFINAE 意味着无法为给定类型实例化的模板也不会。enable_if_c基本上当且仅当其参数为 时才会产生有效类型true。现在我们使用元函数is_default_constructible来测试该类型是否C有默认构造函数。如果是这样,enable_if_c<\xe2\x80\xa6>::type将产生有效类型,否则不会。

\n\n

因此,C++ 编译器只会看到这两个函数之一,即在您的上下文中可用的函数。请参阅文档enable_if有关更多详细信息,

\n