使用可变模板来指定友元类
Using variadic templates to specify friend classes
本文关键字:友元 更新时间:2023-10-16
我正在尝试使用可变模板来指定友元类。我尝试使用以下语法,但它不起作用。
template <class... Args>
struct A {
friend Args...;
};
我试着编写一些变通方法,但似乎并不那么简单,因为友谊不是传递和继承的。因此,问题是,是否有正确的语法或任何变通方法可以使Args中的每个单独类成为a的朋友?
也许以下CRTP变体就足够了:
template<typename Arg> class Abase
{
friend Arg;
virtual int foo(int) = 0; // this is the private interface you want to access
public:
virtual ~Abase() {}
};
template<typename... Args> class A:
public Abase<Args> ...
{
virtual int foo(int arg) { return frobnicate(arg); }
// ...
}
然后,在Args中传递的每个类都可以通过相应的Abase
基类访问该专用接口,例如
class X
{
public:
// assumes X is in the Args
template<typename Args ...> int foo(A<Args...>* p)
{
Abase<X>* pX = p; // will fail if X is not in Args
return pX->foo(3); // works because X is friend of Abase<X>
}
};
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 友元方法作为常量
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误