Search code examples
c++templatesfriendallocator

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


Long story short, here's the problem:

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?
};

Is the only solution to expose the private fields publicly?
How are you supposed to actually to make the conversion constructor?


Solution

  • In the template copy constructor, alloc<T> and alloc<U> are different type, means you can't access the private member of alloc<U> here.

    You can make alloc<U> friend:

    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
    };