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

当您可能只想模板化其中一个时,您正在模板化类和函数。

你是这个意思吗?

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 回答