【发布时间】:2011-04-20 21:45:39
【问题描述】:
我正在编写一段代码,并且已经将我的头撞到众所周知的墙上已经有一段时间了。我对模板的整个概念有点陌生,因此希望能在以下问题上提供任何帮助:
我正在尝试构建一个将分配器作为参数的对象构建器:
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”函数时,出现以下编译错误:“error: expected primary-expression before 'int'”
分配器按预期自行工作,但不能像示例中那样用作模板参数。那么,我可以做些什么来解决这个问题,而不必在分配器中删除模板函数?
我最好使用多态性来发送分配器(基类)对象 指向构建器的指针,但显然您不能拥有虚拟模板功能。 :)
感谢您的时间! :) -麦戈
【问题讨论】:
标签: c++ templates function nested