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?
Given the you have separate files , Ah and Bh 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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.