【问题标题】:Can a class be aware of superclasses when used multiple inheritance?使用多重继承时,一个类可以知道超类吗?
【发布时间】:2019-08-05 15:32:03
【问题描述】:

我正在考虑在我的库设计中使用多重继承。用户定义被描述为 stateless 类(Component1Component2Component3)的组件,每个组件都具有相同的typedefs 和静态成员。请参阅下面的Component1 示例。其他组件类的定义方式相同,定义了同名的子类、typedef和静态成员。

我还希望用户能够将多个组件的组合定义为另一个类 (Combined)。一种方法是通过多重继承(参见下面的定义),但我需要组合类自动了解它所构建的组件。组件的顺序很重要。

struct Component1{
    using MyType = int; //each class defines several standard typedefs
    using return_type = int; 
    struct Parameters {
        constexpr auto static parameter_set = 42;
    }; //classes also define static subclasses
    static return_type myfun(MyType); //and static functions that get defined elsewhere.
};

struct Component2 {/* This class have the same duck-type (public interface) as Base1*/  };

struct Component3 {}; //likewise

struct Combined: public Component1, public Component3, public Component2 {
   //I want this to be automatically generated:
   using members = std::tuple<Component1, Component3, Component2>; 
};

或者也许还有另一种提供类似 API 的方法?

【问题讨论】:

  • 看起来using Combined = Combine&lt;Component1, Component3, Component2&gt;; 将是一个很好的起点。
  • 好的,谢谢!!!这就是SO的惊人力量。在询问后大约 1 分钟内,我得到的答案改变了我看待问题的方式。现在解决方案很简单。再次感谢! @昆汀
  • @LightnessRacesinOrbit 我什至不知道我是怎么养成这种路过提示丢弃习惯的......
  • 我的高度相关问题:stackoverflow.com/q/20798707/2445184 我想,那里的答案也可能对您有所帮助。

标签: c++ c++14


【解决方案1】:

您无法从 C++ 类中检索基类列表(还没有?)。

但是,您可以提供以下形式的Combine 类模板:

template <class... Components>
struct Combine {
    using members = std::tuple<Components...>;

    // ...
};

然后您可以通过以下方式使用它:

using Combined = Combine<Component1, Component3, Component2>;
// or
struct Combined : Combine<Component1, Component3, Component2> {
    // ...
};

【讨论】:

    【解决方案2】:

    一种方式:

    template <class... Components>
    struct Combine : Components... {
        using members = std::tuple<Components...>;
    
        template<class... Args>
        Combine(Args&&... args)
            : Components(args...)...
        {}
    };
    
    struct A { A(int); };
    struct B { B(int); };
    
    struct C : Combine<A, B> {
        using Combine::Combine;
    };
    
    int main() {
        C c(1);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      相关资源
      最近更新 更多