c – 两个不同类的运行时多态性

我有两个B和Y类,我无法根据要求进行更改或编辑.它们具有相同功能但具有不同名称的功能.

我希望有一个通用的接口,在运行时根据一些输入变量选择类,如下面的代码所述.我不确定应该使用哪种设计模式.如何创建WrapperYB类,根据创建的对象选择Y :: show或B ::.

class A
{
public:
    A() {}
    virtual ~A();
    virtual void show() { cout << "show A" << endl;}
};


class B:A
{
public:
    B() {}
    virtual ~B();
    virtual void show() { cout << "show B" << endl;}
};



class X
{
    char m_i;
public:
    Y() {  m_i = 'X';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};

class Y:X
{
public:
    Y() {  m_i = 'Y';}
    virtual void showing() { cout << "showing " << m_i   << endl;}
};



class WrapperYB
{
    // to be implemented

public:
    explicit WrapperYB(const int& type);
    void show();

};

int main(){

    WrapperYB objY(1);

    objY.show(); // must call Y::showing

    WrapperYB objB(0);

    objB.show(); // must call B::show

}

解决方法:

如果您的编译器支持C 17标准,您可以使用std::variant尝试此解决方案.这与@Nicolas的答案中的解决方案类似,但变体将为您处理实现细节,不会使用动态内存分配,并支持复制和分配等其他内容.

#include <variant>
#include <utility>
#include <type_traits>

class WrapperYB {
public:
    using variant_type = std::variant<Y, B>;

    template <typename... Args,
        std::enable_if_t<std::is_constructible_v<variant_type, Args...>>* = nullptr>
    WrapperYB(Args&& ... args) : m_variant(std::forward<Args>(args)...) {}

    variant_type& variant() noexcept { return m_variant; }
    const variant_type& variant() const noexcept { return m_variant; }

    void show()
    { std::visit(ShowImpl{}, m_variant); }

private:
    struct ShowImpl {
        void operator() (Y& y) const { y.showing(); }
        void operator() (B& b) const { b.show(); }
    };

    variant_type m_variant;
};

See the full working example on coliru.

您可以通过让它包含std :: unique_ptr< A>来概括包装器.或std :: unique_ptr< X>代替.

上一篇:Python中的多态性


下一篇:c – 从vector :: iterator转换为vector :: iterator