C++ STL内存分配器编译错误
我正在编写一个与 STL 一起使用的 C++ 自定义分配器。当我将以下代码放入类定义中时,它会编译:
#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
但是当我将其放入单独的 .cpp 文件中时,出现以下错误。我做错了什么?错误出现在 static_cast 行上。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模板必须始终在翻译单元内定义。为了使用模板功能,模板的定义需要放在头文件中,而不是单独的.cpp文件中。
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.
您需要将
typename
放在MyAlloc::pointer
前面。由于MyAlloc
的类型取决于T
,因此编译器不知道pointer
是 typedef 还是成员变量或函数。如果您不写typename
,那么编译器将假定后者。You need to put
typename
in front ofMyAlloc<T>::pointer
. Because the type ofMyAlloc<T>
depends onT
, the compiler doesn't know whetherpointer
is a typedef or a member variable or function. If you don't writetypename
, then the compiler assumes the latter.