Saturday 18 August 2007

Partial template specialization for functions

This post contains highly technical stuff !!!

Recently, I had to create template function with the same name and arguments that would behave in some general way for all data types, except complex numbers. Something like

template<class T> void X(const T& t) { ... }
template<class T> void X(const std::complex<T>& t) { ... }

Nice how it looks (IMHO), such approach does not work. The reason - in C++ template functions do not have partial template specialization. They have overloading. So, basically, I've just created two different functions, and left it up to compiler to choose best one. Since in first case parameter T may as well be complex number, compiler's choice was not what I expected.

The solution: C++ template classes do have partial specialization, use them. The following code would work:

template<class T> struct Y {
  static void Perform(const T& t) { ... }
};
template<class T> struct Y<std::complex<T> > {
  static void Perform(const std::complex<T>& t) { ... }
};

And You may wrap it into the function, something like

template<class T> void X(const T& t) { Y<T>::Perform( t ) };

No comments: