具有静态函数的模板类

template class with static function

本文关键字:静态函数      更新时间:2023-10-16

我想创建一个带有静态函数的模板类

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«

您正在模板化类和函数,而您可能只想模板化其中之一。

这是你的意思吗?

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);

如果只想对函数进行模板化,则可以删除外部模板。