Search code examples
c++templatestemplate-specialization

Explicit Template Function and Method Specialization


I've been looking for a clear answer, and I'm just catching bits and pieces from the web.

I've got a function, and it needs to act differently based on a type variable. The function takes no arguments, so overloading doesn't work, leading to template specialization. E.g.:

//Calls to this function would work like this:
int a = f();
int b = f<int>();
int c = f<char>();
//...

First off, is that even syntactically possible? I feel like it is. Continuing.

I'm having problems defining this function, because I get hung up on the syntax for explicit specialization. I've tried a number of different approaches, but I have yet to get even a simple example to work.

Secondly, I'm trying to (eventually) make that template function into a template method of a (non-template) class. I'll cross that bridge when I come to it.


Solution

  • Well, it is possible but is not one of the nicer things to do. Explicit template function specializations are somewhat of a dark corner, but here is how you do it:

    template< typename T > int f(){ ... }
    
    template<> int f<int>(){ ... }
    template<> int f<char>(){ ... }
    

    Some related reading: http://www.gotw.ca/gotw/049.htm