使类模板成为其自身的朋友,以进行不同的实例化

Make a class template a friend of itself for different instantiation

本文关键字:朋友 实例化      更新时间:2023-10-16

我想让A<T>成为任何类型的TT2A<T2>的朋友。

这可能吗?

谢谢。

测试(也在 godbolt.org(:

template <class T>
class A {
public:
template <typename T2> void test(A<T2>& a) { a.v_ = 2;}
private:
int v_;
template <typename T2> friend A;
};
int main() {
A<int> a;
A<int> b;
b.test(a);
return 0;
}

编译器错误:

<source>:7:28: error: friend type templates must use an elaborated type
template <typename T2> friend A;
^~~~~~~~

它应该是

template <typename T2> friend class A;