Using variadic templates to specify friend classes

半腔热情 提交于 2019-12-04 23:42:08

问题


I'm trying to use variadic templates to specify friend classes. I try with the following syntax, but it doesn't work.

template <class... Args>
struct A {
    friend Args...;
};

I try to code some workarounds, but it seems to be not so simple since the friendship is not transitive and inherited. So the question is if there is a correct syntax or any workaround to make each individual class in Args be a friend of A?


回答1:


Maybe the following CRTP variant would be sufficient for your use:

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); }
  // ...
}

Then each class you pass in Args can access that private interface through the corresponding Abase base class, for example

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


来源:https://stackoverflow.com/questions/23305999/using-variadic-templates-to-specify-friend-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!