模板函数相关编译错误

Template function related compile error

本文关键字:编译 错误 函数      更新时间:2023-10-16

我正在编写一段代码,这段时间我一直在绞尽脑汁。我对模板的整个概念有点陌生,所以我会感谢任何和所有的帮助,我可以在以下问题上得到:

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

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'"

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

我更愿意使用多态性来发送分配器(基类)对象指向构建器的指针,但显然你不能有虚拟模板函数。:)

感谢您的宝贵时间!:)-Maigo

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

c++模板获取方法