Issue with declare friend template class

74 views Asked by At

I have a first class that looks like:

template <typename T1, typename T2> class A

and a second class that looks like:

template <typename T1> class B

Now I would like to declare that A<T1, T2> is always a friend of B<T1>. So I tried:

// B.h

template <typename T1> class B
{
    template <typename T2> friend class A<T1, T2>;

    public:
    ... 
}

But that does not seem to work. What should I do?

1

There are 1 answers

9
Acha Bill On

Given the you have separate files , A.h and B.h and the condition that only A<T1,T2> should be a friend of B<T1>, then :

//B.h
template <typename T>
class B
{
private:
    T x;
public:
    B(T value);
    //note: B<T> befriends A<T,T1>
    template<typename T, typename T1> friend class A;
};
template<typename T>
B<T>::B(T value)
{
    x = value;
}

//A.h
#include "B.h"
template <typename T1, typename T2>
class A
{
public:
    //note B<T1> and A<T1,T2>
    T1 get(B<T1> &b);
};
template<typename T1, typename T2>
T1 A<T1, T2>::get(B<T1>& b)
{
    return b.x;
} 

//test.cpp
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;

int main()
{
    B<int> b(3);
    A<int, char> a;
    cout << a.get(b) << endl;  //3

    return 0;
}
//test.2
B<string> b("test");
A<string,double> a;
cout << a.get(b) << endl; //"test"

//test.3 
B<int> b(3);
A<double,int> a;
cout << a.get(b) << endl; //error: