繁体   English   中英

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

[英]Declaring nested base template class instances the friends of a derived class

假设我有:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM