Harvey Dent
Harvey Dent

Reputation: 339

C++ function template partial specialization

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)

Upvotes: 2

Views: 754

Answers (1)

Barry
Barry

Reputation: 304132

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.

Upvotes: 3

Related Questions