Jens Åkerblom
Jens Åkerblom

Reputation: 908

Friendship Throughout Same Template Class

Consider the following:

template<int N>
class A
{
public:
    A() : i(N) {}

    template<int K>
    void foo(A<K> other)
    {
        i = other.i; // <-- other.i is private
    }

private:
    int i;
};

int main()
{
    A<1> a1;
    A<2> a2;
    a1.foo(a2);

    return 0;
}

Is there a way to make 'other.i' visible without moving member i and foo to a common base class or doing something mad as adding friend class A<1>?

That is, is there a way to make templates of the same template class friends?

Upvotes: 9

Views: 92

Answers (1)

Puppy
Puppy

Reputation: 147056

C++03 did not provide a mechanism for this, but C++11 does.

template<int N2> friend class A;

should friend all instantiations of A.

Upvotes: 10

Related Questions