c++ - 如何检查模板参数是否默认可构造

标签 c++ templates implementation

我正在写一个模板类,想知道模板参数是否是 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但它不起作用,准确地说,如果返回默认可构造的,即使对于那些不是的类,我不知道为什么会这样。

最佳答案

这是 SFINAE 的经典案例和 enable_if .

在另一个答案中,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/

相关文章:

c - C 中最快的 fgets 实现

java - 适合实时客户端/服务器物理模拟的设计模式?

c++ - 如何捕捉这个错误? [C++]

c# - 将字符串作为参数从 C# 传递到 C++ 中的回调函数

c++ - 在 find_if 中使用仿函数

c++ - 从非类型模板参数声明 constexpr 数组的可移植方式

c++ - 在无限循环中暂停 QThread

c++ - 从带有空格的字符串中获取整数的最佳方法?

c++ - 为什么构造不完整类型的 std::unique_ptr 编译?

c++ - 堆栈推送操作实现不起作用