Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do template specializations require template<> syntax?

I have a visitor class resembling this:

struct Visitor 
{
    template <typename T>
    void operator()(T t)
    {
        ...
    }

    void operator()(bool b)
    {
        ...
    }
};

Clearly, operator()(bool b) is intended to be a specialization of the preceding template function.

However, it doesn't have the template<> syntax that I'm used to seeing before it, declaring this as a template specialization. But it does compile.

Is this safe? Is this correct?

like image 860
Drew Dormann Avatar asked Jun 01 '09 22:06

Drew Dormann


Video Answer


1 Answers

Your code is not a template specialization, but rather a non-templated function. There are some differences there. The non-templated operator() will take precedence over a templated version (for an exact match, but type conversions will not take place there) but you can still force the templated function to be called:

class Visitor
{
public: // corrected as pointed by stefanB, thanks
   template <typename T>
   void operator()( T data ) {
      std::cout << "generic template" << std::endl;
   }
   void operator()( bool data ) {
      std::cout << "regular member function" << std::endl;
   }
};
template <> // Corrected: specialization is a new definition, not a declaration, thanks again stefanB 
void Visitor::operator()( int data ) {
   std::cout << "specialization" << std::endl;
}
int main()
{
   Visitor v;
   v( 5 ); // specialization
   v( true ); // regular member function
   v.operator()<bool>( true ); // generic template even if there is a non-templated overload
   // operator() must be specified there (signature of the method) for the compiler to 
   //    detect what part is a template. You cannot use <> right after a variable name
}

In your code there is not much of a difference, but if your code needs to pass the template parameter type it will get funnier:

template <typename T>
T g() { 
   return T();
}
template <>
int g() {
   return 0;
}
int g() {
   return 1;
}
int main()
{
   g<double>(); // return 0.0
   g<int>(); // return 0
   g(); // return 1 -- non-templated functions take precedence over templated ones
}
like image 86
David Rodríguez - dribeas Avatar answered Oct 04 '22 21:10

David Rodríguez - dribeas