friend templates

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<typename T> 
class A {
//...
};

template<typename T> 
class B {
//...
};


template<typename T1, typename T2> 
void f(A<T1>, B<T2>){
//...
}



I want to make the template f the friend of A<T1>,
what should I write in definition of class A<T1>?
Last edited on
The problem is how to declare typename T2 in A
I want to make the template f the friend of A<T1>

Keep in mind that when friending function templates, you can only friend the entire template, or its explicit specialization (e.g. friend void f<> (A, B<int>);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template<typename T>
class B { };

template<typename T>
class A {
    int private_n;

    // this friends every f 
    template<typename T1, typename T2>
    friend void f(A<T1>, B<T2>);
};

template<typename T1, typename T2>
void f(A<T1> a, B<T2>){
     a.private_n = 1;
}

int main()
{
    A<int> a;
    B<double> b;

    f(a, b);
}


Alternatively, you could choose to generate a separate friend template for each T1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template<typename T>
class B { };

template<typename T>
class A {
    int private_n;

    // this generates a separate f for every T1
    template<typename T2>
    friend void f(A a, B<T2>) {
        a.private_n = 2;
    }
};


int main()
{
    A<int> a;
    B<double> b;

    f(a, b);
}
Last edited on
Thanks. I'm curious if f can be friend of both A<T1> and B<T2>?
sure:
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
template<typename T>
class A; // declares A as a class template

template<typename T>
class B {
    int private_n;

    template<typename T1, typename T2>
    friend void f(A<T1>, B<T2>); // friends every f
};

template<typename T>
class A {
    int private_n;

    template<typename T1, typename T2>
    friend void f(A<T1>, B<T2>); // friends every f
};

template<typename T1, typename T2>
void f(A<T1> a, B<T2> b){ // defines f
     a.private_n = 1;
     b.private_n = 2;
}

int main()
{
    A<int> a;
    B<double> b;

    f(a, b);
}
Topic archived. No new replies allowed.