make a template class a friend of two class

Imagine we have three template classes. The second class `B` should access private member of class `A` and class `C` should access private members of both classes `A` and `B`. I defined class `B` as `friend class` for class `A` and classes `B` and `C` as `friend` classes of class `A`.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
template<int d, class T>
class B;

template<int d, class T>
class C;

template<int d>
class A
{
  private:
    int x;
    ...
  public:
    ...
    template <int, class T>
    friend class B;

    template <int, class T>
    friend class C;
};

template<int d, class T>
class B
{
  private:
     A<d>* a;

  public:
   ...
  friend class C<d, T>;

};

template<int d, class T>
class C
{
   private:
     B<d, T>* b;
   public:
     ...
};

int main()
{
  B<2, double> b;
  C<2, double> c;
}

in linking process, class C can not access private member of class A (`A::x`), but class B can, i.e. class C can access `B::a` but not `A::x`. The error is `A::x is private within this context`
Last edited on
1
2
3
4
template <int, class T>
friend class C ;
               ^
     You forgot the semicolon! 


Another problem with your code is that you do not specify the template arguments everywhere, such as in main().
Thanks for pointing out. I just corrected it.
Glad I could help. :) If you have no further questions related to this you might want to mark the thread as solved.
No I still have the problem. It was not the source of problem. I only thanks for correction of the question. It is a simple example of the problem I face and since the original code is quite large, I did not post it here.
It seemed to work when I tried... Please post an example of accessing a private variable that you think should work but doesn't.
Last edited on
Topic archived. No new replies allowed.