Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Jens Åkerblom Avatar asked Dec 07 '12 21:12

Jens Åkerblom


1 Answers

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.

like image 98
Puppy Avatar answered Oct 13 '22 21:10

Puppy