Template class member specialization for template class parameter type

I have a Matrix template template. I want to specialize a function for a complex of types, where T can be anything. I tried this:

  6 template <typename T>
  7 class Matrix {
  8       public :
  9             static void f();
 10 };          
 11 template<typename T> void Matrix<T>::f() { cout << "generic" << endl; }
 12 template<> void Matrix<double>::f() { cout << "double" << endl; }
 13 template<typename T> void Matrix<std::complex<T> >::f() { cout << "complex" << endl; }

Line 13 does not compile. How can i do this?

+5
source share
3 answers

In fact, I found a smart way to do this through Boost. Since I don't want my library to depend on Boost, here is the code:

template <class T, T val> struct integral_constant
{
      typedef integral_constant<T, val> type;
      typedef T value_type;
      static const T value = val;
};    
typedef integral_constant<bool, true>  true_type;
typedef integral_constant<bool, false> false_type;
template <typename T> struct is_complex : false_type{};
template <typename T> struct is_complex<std::complex<T> > : true_type{};

template <typename T>
class Matrix {
      public :
            static void f() { f_( typename is_complex<T>::type() ); }
      private :
            static void f_( true_type ) { cout << "generic complex" << endl; }
            static void f_( false_type ) { cout << "generic real" << endl; }
};          
template<> void Matrix<double>::f() { cout << "double" << endl; }

That way, I can use function overloading and a template to achieve my goal.

+1
source

11 12 , ++ Standard 14.7/3 (14.5.2/2 ). 13 , ( , std::complex<T>, T). .

+3

, , :

#include <iostream>
#include <complex>
using namespace std;

template <typename T>
class Matrix {
public :
    static void f();
};

template<typename T> void Matrix<T>::f() { cout << "generic" << endl; }
template<> void Matrix<double>::f() { cout << "double" << endl; }

template <typename T>
class Matrix<std::complex<T> > {
public:
    static void f() { cout << "complex" << endl; }
};

int main(void) {
  Matrix<complex<double> >::f();
  return 0;
}
0

All Articles