Question

Below I have 3 prototypes. I expected the first one (commented out) to work, but that's the only one that doesn't work (see comments in code for errors). Even more surprising to me is that either of the following 2 work, even when both are present.

/////////////////////////////////////////////////
// Prototypes:
/////////////////////////////////////////////////
//  Causes "ambiguous call to overloaded function" at the call site when when one or both  
//  of the below prototypes is also present. Otherwise causes unresolves external
//template<typename T> void func(); 

//  Okay, can have this one AND/OR the below declaration
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func();

//  Also okay, can have this one AND/OR the above declaration
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func();


int main()
{
    func<int>();
}


/////////////////////////////////////////////////
// Definitions:
/////////////////////////////////////////////////
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func() {}

template<typename T> typename std::enable_if<!std::is_integral<T>::value, void>::type func() {}

Which is the correct prototype, and why doesn't the first one work? I'm using VS2010 & VS2012

Was it helpful?

Solution

The first one causes the error because it declares a different function template. To put it simply, it is different because all the enable_if thingies are part of its signature, not just the final type it resolves to.

You never provide a definition for that first template declaration, and that's why you get an "unresolved external" error if you don't put the others in.

If you put the others in, now you have one of the others plus this one as a candidate, and both are viable, and not ordered. That's why you get an "ambiguous call" error.

The correct way is to declare the ones you define, i.e., exactly what you have uncommented right now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top