使用可变参数模板来指定好友类 [英] Using variadic templates to specify friend classes

查看:75
本文介绍了使用可变参数模板来指定好友类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用可变参数模板来指定好友类。我尝试使用以下语法,但它不工作。

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

我尝试编写一些解决方法,但它似乎并不那么简单,因为友谊是不可传递的并继承。所以问题是如果有一个正确的语法或任何解决方法,使每个类在Args是A的朋友。

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?

推荐答案

可能以下CRTP变体足以供您使用:

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

Args可以通过相应的 Abase 基类访问该私有接口,例如

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

这篇关于使用可变参数模板来指定好友类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆