C++ STL内存分配器编译错误

发布于 2024-08-19 22:27:13 字数 856 浏览 3 评论 0原文

我正在编写一个与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪痕残 2024-08-26 22:27:13

模板必须始终在翻译单元内定义。为了使用模板功能,模板的定义需要放在头文件中,而不是单独的.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.

小情绪 2024-08-26 22:27:13

您需要将 typename 放在 MyAlloc::pointer 前面。由于 MyAlloc 的类型取决于 T,因此编译器不知道 pointer 是 typedef 还是成员变量或函数。如果您不写typename,那么编译器将假定后者。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文