模板函数相关的编译错误

时间:2011-04-20 21:45:40

标签: c++ templates function nested

我正在编写一段代码,并且已经在很长一段时间内对抗众所周知的墙了。我对模板的整个概念都不熟悉,所以我会很高兴能够解决以下问题:

我正在尝试构建一个对象构建器,它将分配器作为参数:

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'之前预期的primary-expression”

分配器按预期自行工作,但不能像示例中那样用作模板参数。那么,我有什么办法可以解决这个问题,而不必在分配器中删除模板函数吗?

最好我喜欢使用多态来发送一个allocator(基类)对象 指向构建器的指针,但显然您不能拥有虚拟模板函数。 :)

感谢您的时间! :) -Maigo

1 个答案:

答案 0 :(得分:3)

    int* i = a.template allocate_object<int>();

C++ template gotchas