How to check if a template argument is constructive by default

I am writing a template class and want to find out if the template argument is default constructible , is there a way to do this?

The code is as follows

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

Update: I tried to use the code provided in this question , but it does not work, to be precise, if the default return is constructive even for those classes that are not, I have no idea why this is happening.

+4
source share
2 answers

This is a classic case for SFINAE and enable_if .

In another answer, Potatoswatter already posted a trait of type is_default_constructible , which 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 T return type (thanks to DeadMG), you can omit the 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 that cannot be created for this type will not. enable_if_c basically casts to a valid type if and only if its argument is true . Now we use metafunction is_default_constructible to check if type C default constructor. If so, enable_if_c<…>::type will result in a valid type, otherwise it will not.

The C ++ compiler, thus, will see only one of two functions to use one that can be used in your context. See the enable_if documentation for more details.

+3
source

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

In any case, this specific question is answered by <here

+1
source

Source: https://habr.com/ru/post/1335241/


All Articles