模板函数相关编译错误

发布于 2024-11-03 00:53:20 字数 772 浏览 5 评论 0原文

我正在编写一段代码,并且已经用头撞墙很长一段时间了。我对模板的整个概念有点陌生,因此希望我能在以下问题上获得任何和所有帮助:

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

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 技术交流群。

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

发布评论

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

评论(1

空心空情空意 2024-11-10 00:53:20
    int* i = a.template allocate_object<int>();

C++ 模板陷阱

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

C++ template gotchas

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