2

Basically I implement my own memory allocation function Malloc(), which is

void Malloc(size_t size);

Now I want to implement my own New and NewArray function, I declare those two functions like this:

// template 
  template <class T>
  T* New(void);
  template <class T>
  T* NewArray(unsigned int num);

And implementations are:

template <class T>
T* MemPool::New<T>()
{
  return (T *)Malloc(sizeof(T));
}

template <class T>
T* MemPool::NewArray<T>(unsigned int num)
{
  if(num < 0)
    return NULL;
  return (T*) Malloc(sizeof(T) * num);
}

But compilation fails with this:

MP.cpp:482:20: error: function template partial specialization ‘New<T>’ is not allowed
 T* MemPool::New<T>()
                    ^
MP.cpp:488:41: error: function template partial specialization ‘NewArray<T>’ is not allowed
 T* MemPool::NewArray<T>(unsigned int num)
Laurel
  • 5,965
  • 14
  • 31
  • 57
Harvey Dent
  • 327
  • 2
  • 14

1 Answers1

3

You have an extra <T> here:

template <class T>
T* MemPool::New<T>()
//             ^^^

Should just be:

template <class T>
T* MemPool::New()

And the same for NewArray.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • Thanks! The compilation passed, but if I use those two functions like this int *p2 =mp->New(); char *p3 = mp->NewArray(10); It has another compilation problem: undefined reference to `int* MemPool::New()' – Harvey Dent Jan 30 '15 at 01:26
  • 1
    @MartinGGWW Because [templates must be defined in the header](http://stackoverflow.com/q/495021/2069064). – Barry Jan 30 '15 at 01:30
  • it works after I move them to header file. Thanks for your advice and the link too! – Harvey Dent Jan 30 '15 at 01:53