模板函数相关编译错误
我正在编写一段代码,并且已经用头撞墙很长一段时间了。我对模板的整个概念有点陌生,因此希望我能在以下问题上获得任何和所有帮助:
我正在尝试构建一个对象生成器,该对象生成器将分配器作为参数:
class Allocator {
public:
allocate(unsigned int size, unsigned int alignment);
template <class T>
T* allocate_object() { return allocate(sizeof(T), alignof(T)); }
};
template <class ALLOCATOR>
class Builder {
public:
Builder(ALLOCATOR& a) : a(a) {}
void build_something() {
int* i = a.allocate_object<int>();
}
private:
ALLOCATOR& a;
};
当我尝试调用我的分配器使用“build_something”函数时出现以下编译错误:“错误:'int'之前预期的主表达式”
分配器按预期自行工作,但不能用作模板参数如示例所示。那么,我可以做些什么来解决这个问题,而不必在分配器中删除模板函数吗?
最好我想使用多态性来发送分配器(基类)对象 指向构建器的指针,但显然你不能拥有虚拟模板函数。 :)
谢谢你的时间! :) -麦戈
I'm working on a piece of code and have been banging my head against the proverbial wall for quite some time now. I am kind of new to the whole concept of templates and so would appreciate any and all help I can get on the following problem:
I am trying to build a object builder that takes an allocator as argument as such:
class Allocator {
public:
allocate(unsigned int size, unsigned int alignment);
template <class T>
T* allocate_object() { return allocate(sizeof(T), alignof(T)); }
};
template <class ALLOCATOR>
class Builder {
public:
Builder(ALLOCATOR& a) : a(a) {}
void build_something() {
int* i = a.allocate_object<int>();
}
private:
ALLOCATOR& a;
};
When I try to call the 'build_something' function with my allocator i get the following compilation error: "error: expected primary-expression before 'int'"
The allocator works on its own as intended but can not be used as a template argument as in the example. So, is there something I can do to fix this without having to drop the template function in the allocator?
Preferably I would have liked to use polymorphism to send an allocator (base class) object
pointer to the builder but apparently you can't have virtual template functions. :)
Thanks for the time! :)
-Maigo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++ 模板陷阱
C++ template gotchas