我该如何使我的分配器可重新绑定?我能做到这一点,同时保持其字段的私有

How am I supposed to make my allocator rebindable? Can I do it while keeping its fields private?

本文关键字:这一点 字段 我的 分配器 何使 绑定 新绑定      更新时间:2023-10-16

长话短说,问题是这样的:

template<class T>
struct alloc
{
    template<class U>
    alloc(alloc<U> const &other) : foo(other.foo) { }  // ERROR: other.foo is private 
    template<class U> struct rebind { typedef alloc<U> other; };
private:
    pool<T> *foo;  // do I HAVE to expose this?
};

是公开私有字段的唯一解决方案吗?
你应该如何创建转换构造函数呢?

在模板复制构造函数中,alloc<T>alloc<U>是不同类型的,这意味着你不能在这里访问alloc<U>的私有成员。

你可以让alloc<U>成为朋友:

template<class T>
struct alloc
{
    ... ...
    template <typename U>
    friend struct alloc;
    alloc(alloc<U> const &other) : foo(other.foo) {} // possible to access other.foo now
};

我自己的猜测是这是不可能的,您应该使用转换操作符:

template<class U>
operator alloc<U>() const { return alloc<U>(this->foo); }

但我希望有更好的答案…