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