使用可变模板来指定友元类

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>
  }
};