如何检查模板参数是否是默认可构造的 [英] How to check if a template argument is default constructible

查看:148
本文介绍了如何检查模板参数是否是默认可构造的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个模板类,想知道模板参数是否为 default constructible 有什么办法吗?

I am writing a template class and want to find out whether template argument is default constructible is there any way to do it ?

代码如下

template <class C>
class A
{

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

更新:我尝试使用这个问题中给出的代码但它不工作,默认构造即使对于那些不是的类,我不知道为什么会发生。

Update: I have tried using code given in this question but it doesn't work, to be precise if return default constructible even for those classes which aren't, I have no idea why is that happening.

推荐答案

SFINAE enable_if

在另一个答案,Potatoswatter已经发布了一个类型trait is_default_constructible 可在此处重复使用:

In another answer, Potatoswatter has already posted a type trait is_default_constructible that can be reused here:

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)可以省略虚拟默认参数:

Or, if your function has a non-void return type T (thanks to DeadMG) you can omit the dummy default argument:

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 将产生有效的类型,否则不会。

SFINAE means that a template which cannot be instantiated for a given type, will not. enable_if_c basically results in a valid type if and only if its argument is true. Now we use the metafunction is_default_constructible to test whether the type C has a default constructor. If so, enable_if_c<…>::type will result in a valid type, otherwise it will not.

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

The C++ compiler will thus only see one of the two functions, to wit the one that is usable in your context. See the documentation of enable_if for more details.

这篇关于如何检查模板参数是否是默认可构造的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆