MyNiceDisplayName MyNiceDisplayName - 3 years ago 114
C++ Question

Type SFINAE in VS2015 compiles, but generates error

I have made two test classes:

class Class1
{
public:
Class1(int a) {}
};

class Class2
{
public:
Class2() {}
};


And two template functions using type SFINAE to decide which to use. The second one will "fail" if T is not default constructible.

template<typename T>
T* CreateInstanceTest(char*[!std::is_default_constructible<T>::value] = 0) { return nullptr; }

template<typename T>
T* CreateInstanceTest(char*[std::is_default_constructible<T>::value] = 0) { return new T(); }


Then I do this:

Class1* obj1 = CreateInstanceTest<Class1>();
Class2* obj2 = CreateInstanceTest<Class2>();


Which generates the error "more than one instance of overloaded function "CreateInstanceTest" matches the argument list".

However, it compiles fine and works as expected. obj1 becomes null and obj2 is created properly.

Why does this happen? And is there some way to get around it?

VTT VTT
Answer Source

It is an Intellisense error, not a build error. Intellisense is not perfect, however as a workaround you can improve deduction code:

template<typename T> typename ::std::enable_if_t
<
    !::std::is_default_constructible<T>::value
,   T *
>
CreateInstanceTest(void) { return nullptr; }

template<typename T> typename ::std::enable_if_t
<
    ::std::is_default_constructible<T>::value
,   T *
>
CreateInstanceTest(void) { return new T(); }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download