Composition of patterns and transitivity of friendship

I have a container with private data and a class of friends accessing the private data:

template<class T>
class Container
{
    friend typename T::MyAccessor;
    vector<T> _data;
};

template<class T>
class Accessor
{
public:
    void doSomething(Container<T> *c)
    {
        cout << c->_data.size() << endl;
    }
};

template<class T, template<typename> class CustomAccessor>
struct MyBase
{
    typedef Container<T> MyContainer;
    typedef CustomAccessor<T> MyAccessor;
};

      

Now I want to create an accessory composition like this:

template<
    template<typename> class First
    ,template<typename> class Second 
    ,class T
>
class Composite
{
public:
    typedef First<T> MyFirst;
    typedef Second<T> MySecond;

    void doSomething(Container<T> *c)
    {
        MyFirst a;
        a.doSomething(c);

        MySecond b;
        b.doSomething(c);
    }
};

template<class T>
class DoubleAccessor : public Composite<Accessor, Accessor, T> {};

      

but the friendship is not transitive and is composed, and access to them is not available to the personal data of the access container. Is there a way to get around this without exposing the container's identity to everyone?

+3


source to share


1 answer


What if you just declare class Accessor

as friend

yours class Container

:

template<class T>
class Container {
    template<class T1> friend class Accessor;
    std::vector<T> _data;
};

template<class T>
class Accessor {
public:
    void doSomething(Container<T> *c) {
        std::cout << c->_data.size() << std::endl;
    }
};

template<class T, template<typename> class CustomAccessor = Accessor>
struct MyBase {
    typedef Container<T> MyContainer;
    typedef CustomAccessor<T> MyAccessor;
};

template<class T, template<typename> class First = Accessor, template<typename> class Second = Accessor>
class Composite {
public:
    typedef First<T> MyFirst;
    typedef Second<T> MySecond;

    void doSomething(Container<T> *c) {
        MyFirst a;
        a.doSomething(c);

        MySecond b;
        b.doSomething(c);
    }
};

      



LIVE DEMO

+1


source







All Articles