2

静的関数を持つテンプレート クラスを作成したかった

template <typename T>
class Memory
{
 public:
  template < typename T>
  static <T>* alloc( int dim )
  {
    T *tmp = new T [ dim ];
    return tmp;
  };
}

しかし、私はいつも得ます

int *a = Memory::alloc<int>(5)

私は偶然に何を知りません..

 »template<class T> class Memory« used without template parameters
 expected primary-expression before »int«
 Fehler: expected »,« or »;« before »int«
4

1 に答える 1

6

クラスと関数の両方をテンプレート化していますが、そのうちの 1 つだけをテンプレート化したい場合があります。

これはあなたが意味するものですか?

template <typename T>
class Memory
{
 public:
  static T* alloc( int dim )
  {
    T *tmp = new T [ dim ];
    return tmp;
  };
}

int *a = Memory<int>::alloc(5);

両方を含む正しいバージョンは次のとおりです。

template <typename T>
class Memory
{
 public:
  template <typename U>
  static U* alloc( int dim )
  {
    U *tmp = new U [ dim ];
    return tmp;
  };
}

int *a = Memory<float>::alloc<int>(5);

関数をテンプレート化するだけの場合は、外側のテンプレートを削除できます。

于 2012-04-28T12:55:01.430 に答える