【问题标题】:Declaring nested base template class instances the friends of a derived class将嵌套的基模板类实例声明为派生类的朋友
【发布时间】:2019-09-15 12:01:54
【问题描述】:

假设我有:

class A {};

template <typename T> class B {};

template <typename T> class C {};

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

有没有办法为class D 构造一个朋友声明,这样A 类型的实例就是D 的朋友。 B&lt;A&gt; 类型的实例是 D 的朋友。 C&lt;B&lt;A&gt;&gt; 类型的实例是 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();
}

【问题讨论】:

  • 看起来你正在编写 mixins。如果您使用多重继承,它可能会更干净。不过,这不会摆脱多个朋友声明。

标签: c++ templates inheritance friend


【解决方案1】:

恐怕你必须单独为每个班级加好友。你不能继承友谊,所以我认为不可能通过一个朋友声明来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2019-01-29
    • 2018-08-23
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    相关资源
    最近更新 更多