Why doesn't my function skip trying to resolve to the incompatible template function, and default to resolving to the regular function? [duplicate]

StackOverflow https://stackoverflow.com/questions/11938359

Question

std::string nonSpecStr = "non specialized func";
std::string const nonTemplateStr = "non template func";

class Base {};
class Derived : public Base {};

template <typename T> std::string func(T * i_obj)
{ 
   ( * i_obj) += 1;
   return nonSpecStr; 
}

std::string func(Base * i_obj) { return nonTemplateStr; }

void run()
{
   // Function resolution order
   // 1. non-template functions
   // 2. specialized template functions
   // 3. template functions
   Base * base = new Base;
   assert(nonTemplateStr == func(base));

   Base * derived = new Derived;
   assert(nonTemplateStr == func(derived));

   Derived * derivedD = new Derived;

   // When the template function is commented out, this
   // resolves to the regular function. But when the template
   // function is uncommented, this fails to compile because
   // Derived does not support the increment operator. Since
   // it doesn't match the template function, why doesn't it
   // default to using the regular function?
   assert(nonSpecStr == func(derivedD));
}
Was it helpful?

Solution

Template argument deduction makes your template function an exact match with by deducing T as Derived. Overload resolution only looks at the signature of the function, and doesn't look at the body at all. How else would it work to declare a function, call it in some code, and define it later?

If you actually want this behaviour of checking the operations on a type, you can do so with SFINAE:

// C++11
template<class T>
auto f(T* p)
    -> decltype((*p)+=1, void())
{
  // ...
}

This will make substitution fail if T doesn't support operator+=.

OTHER TIPS

Type T can be an exact match which will not require an implicit conversion in the first place, so it is preferable to your Base class version of the non-template function.

You can specialize the template function for a type that doesn't meet the implicit contract and have it call the non templated function instead if you find this problematic. Equally, you can provide non-templated versions matching the exact derived classes you will use so that implicit conversions are not required. Both of these options are more painful than just not using that operator though. Code your templates so their implicit template contracts require as little as possible :)

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