声明嵌套的基础模板类实例为派生类的朋友

时间:2019-04-26 01:40:16

标签: c++ templates inheritance friend

假设我有

class A {};

template <typename T> class B {};

template <typename T> class C {};

class D : public C<B<A>> {
    //friend ... ??
};

有没有一种方法可以为class D构造一个朋友声明,使得类型A的实例是D的朋友。类型B<A>的实例是D的朋友。类型C<B<A>>的实例是D的朋友。依此类推,自动生成任意数量的嵌套模板类型,而不必手动在D中使用多个朋友声明来指定?

编辑:要添加一些上下文,所需的应用程序是使用带有公共函数的“链接” CRTP接口样式,这些公共函数在实现类中调用受保护的“替代”函数,额外的“朋友”声明有点丑陋,但不是我猜这种样式的复合接口的长度太长了。

#include <iostream>

template <typename T>
struct static_base {
  T& self() { return static_cast<T&>(*this); }
  T const& self() const { return static_cast<T const&>(*this); }
};

template <typename Derived>
class InterfaceBase : public static_base<Derived> {};

template <typename Derived>
class Interface1 : public Derived {
 public:
  void foo() { this->self().foo_(); }
};

template <typename Derived>
class Interface2 : public Derived {
 public:
  void bar() { this->self().bar_(); }
};

template <typename Derived>
class Interface3 : public Derived {
 public:
  void baz() { this->self().baz_(); }
};

class Impl : public Interface3<Interface2<Interface1<InterfaceBase<Impl>>>> {
    friend Interface3<Interface2<Interface1<InterfaceBase<Impl>>>>;
    friend Interface2<Interface1<InterfaceBase<Impl>>>;
    friend Interface1<InterfaceBase<Impl>>;

    protected:
        void foo_() { std::cout << "foo" << "\n"; }
        void bar_() { std::cout << "bar" << "\n"; }
        void baz_() { std::cout << "baz" << "\n"; }
};

int main() {
    auto impl = Impl();
    impl.foo();
    impl.bar();
    impl.baz();
}

1 个答案:

答案 0 :(得分:1)

恐怕您必须分别与每个班级交朋友。您无法继承友谊,因此我认为不可能用一个朋友声明来做到这一点。

相关问题