朋友&&模板
Friend && Template
我实际上是想让一个模板类与另一个模板类成为朋友。像这样:
#include <iostream>
template < typename T >
class Test1 {
private:
static int wantToBeFriend;
};
template < typename T >
int Test1<T>::wantToBeFriend = 1;
template < typename T >
class Test2 {
friend class Test1<T>;
public:
void run() {
std::cout << Test1<T>::wantToBeFriend << std::endl;
}
};
int main()
{
Test1<int> test1;
Test2<int> test2;
test2.run();
return 0;
}
但我做不到,gcc 说int Test1<T>::wantToBeFriend is private
.有人知道如何实现这一目标吗?
谢谢
友谊不会像你试图让它工作的方式那样工作。 当你有
friend class Test1<T>;
这意味着Test1<T>
可以访问Test2<T>
的私人成员。 它不允许Test2<T>
访问Test1<T>
的私人成员。 如果是这样,那么拥有私人成员就没有意义了,因为您可以让自己成为该类的朋友并访问它们。
如果我们像这样切换它
template < typename T >
class Test2;
template < typename T >
class Test1 {
friend class Test2<T>;
private:
static int wantToBeFriend;
};
然后代码编译得很好,就像现在一样Test2<T>
可以访问私有成员(实时示例)。
你需要反过来做。 Test1
需要将Test2
声明为友元类:
#include <iostream>
template <typename T> class Test2;
template < typename T >
class Test1 {
template <typename U> friend class Test2;
private:
static int wantToBeFriend;
};
template < typename T >
int Test1<T>::wantToBeFriend = 1;
template < typename T >
class Test2 {
public:
void run() {
std::cout << Test1<T>::wantToBeFriend << std::endl;
}
};
int main()
{
// Test1<int> test1;
Test2<int> test2;
test2.run();
return 0;
}
现场演示
相关文章:
- 一位朋友将模板函数缩写为clang和gcc
- 在朋友类中使用模板
- 限制多模板参数朋友函数可访问的类实例的范围
- 如何使专用函数模板成为某个类的朋友?
- c ++如何将模板应用于模板类的孩子/朋友?
- 如何将一个部分专用的模板类的朋友变成另一个部分专用的模板类?
- 使类模板成为其自身的朋友,以进行不同的实例化
- G++ 和 CLang++ 在模板类中定义了朋友模板函数的不同行为
- 如何在模板中编写朋友(操作员)方法
- 如何朋友模板类功能
- 在模板类中编写朋友函数声明的正确方法是什么?
- C 朋友操作员模板专业化
- 朋友和模板在C++
- 正确的朋友模板函数语法
- C 朋友模板功能错误
- 在非板班上的模板朋友类,朋友还使用该类
- 如何在模板类中声明特定于类型的模板朋友函数
- 非常不平凡的模板朋友声明
- 模板朋友类和的C++错误
- C++模板朋友函数未链接