How to check if a template argument is default constructible

时光总嘲笑我的痴心妄想 提交于 2019-12-09 13:17:20

问题


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

The code is something like following

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.


回答1:


This is a classical case for SFINAE and enable_if.

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;
}

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 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.

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.




回答2:


This is a case of SFINAE, you use a function overload, one that takes ... as a parameter, one that calls the method you are looking for.

In any case this particular question is answered `here



来源:https://stackoverflow.com/questions/4669131/how-to-check-if-a-template-argument-is-default-constructible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!