Question

I'm writing a C++ custom allocator for use with STL. When I put the following code in the class definition, it compiles:

#include "MyAlloc.hpp"

#if 1
template <typename T>
typename MyAlloc<T>::pointer
MyAlloc<T>::allocate(size_type n, MyAlloc<void>::const_pointer p) {
  void *ptr = getMemory(n*sizeof(T));

  typename MyAlloc<T>::pointer tptr = static_cast<MyAlloc<T>::pointer>(ptr);
  return tptr;
}
#endif

But when I put it in a separate .cpp file, I get the following error. What am I doing wrong? The error is on the static_cast line.

g++ -c MyAlloc.cpp
MyAlloc.cpp: In member function ‘typename MyAlloc<T>::pointer MyAlloc<T>::allocate(size_t, const void*)’:
MyAlloc.cpp:9: error: expected type-specifier
MyAlloc.cpp:9: error: expected `>'
MyAlloc.cpp:9: error: expected `('
MyAlloc.cpp:9: error: expected `)' before ‘;’ token
make: *** [MyAlloc.o] Error 1

PT

Was it helpful?

Solution

Templates must always be defined within a translation unit. In order to use the template function, the definition of the template needs to go in the header file, not a separate .cpp file.

OTHER TIPS

You need to put typename in front of MyAlloc<T>::pointer. Because the type of MyAlloc<T> depends on T, the compiler doesn't know whether pointer is a typedef or a member variable or function. If you don't write typename, then the compiler assumes the latter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top