模板类参数类型的模板类成员的专门化

Max*_*ime 5 c++ templates function member

我有一个模板类Matrix.我想专门为类型复杂的函数,其中T可以是任何东西.我试过这个:

  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; }
Run Code Online (Sandbox Code Playgroud)

第13行无法编译.我怎样才能做到这一点 ?

Max*_*ime 1

事实上,我通过 Boost 找到了一个巧妙的方法。由于我不希望我的库依赖于 Boost,因此代码如下:

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; }
Run Code Online (Sandbox Code Playgroud)

这样,我就可以使用函数重载和模板来实现我的目标。