5

テンプレート化されたクラス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; }

13行目はコンパイルされません。どうやってやるの ?

4

3 に答える 3

3

11行目と12行目には、C++標準14.7/ 3で許可されているクラステンプレートのメンバーに対する明示的な特殊化の宣言があります(14.5.2/2にも良い例が含まれています)。std::complex<T>13行目では、クラステンプレートを部分的に特殊化しようとしていますが、このフォームでは許可されていません(これは、まだ依存しているため、型全体がわからないため、部分的な特殊化ですT)。クラス全体を部分的に専門化する必要があります。

于 2010-05-12T19:28:25.600 に答える
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; }

このようにして、関数のオーバーロードとテンプレートを使用して、目標を達成できます。

于 2010-05-13T12:07:54.490 に答える
0

リンクされた回答で説明されているように、実行する必要があるのは、単純な関数ではなく、クラス全体を特殊化することです。

#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;
}
于 2010-05-12T19:25:55.933 に答える