Templates and friend declarations

Greetings,

While designing part of my game framework I came across a problem with templates and friend declarations within them. I've sumed up the problem into these few lines of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//...

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

    private:
        int I;
};

class B {};

template<class X>
class C
{
    friend class A<X>;

    public:
        void f(A<B> & a) { cout << "A::I = " << a.I << endl; }
};

int main()
{
    A<B> Ab(1);
    C<B> Cb;
    
    Cb.f(Ab);
}


The code yields the following compiling error:
error: 'int A<B>::I' is private

I've declared C<X> as a friend of A<X>, so why is this happening? What am I missing on templates and friend declarations?

Thanks in advance and Best Regards,
-Deimos
A class declares its friends, it doesn't declare what other classes it's friends of. In your code, you're not declaring C to be a friend of A; you're declaring A to be a friend of C. Friendship is a one-directional property. If A is a friend of C, then A has access to C's private members, but the opposite is not true. Making A a friend of C doesn't make C a friend of A.
Topic archived. No new replies allowed.