加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在运行时为调用函数选择对象,没有基类和模板

发布时间:2020-12-16 09:59:51 所属栏目:百科 来源:网络整理
导读:我有两个具有相同接口方法的类: struct ImplGenerated { int foo(int x,int y); void bar(double x); ....};struct ImplCustom { int foo(int x,int y); void bar(double x); .....}; 和类包装器: struct Wrapper { Wrapper(ImplGenerated * i): m_generat
我有两个具有相同接口方法的类:

struct ImplGenerated {
    int foo(int x,int y);
    void bar(double x);
    ....
};

struct ImplCustom {
    int foo(int x,int y);
    void bar(double x);
    .....
};

和类包装器:

struct Wrapper {
    Wrapper(ImplGenerated * i): m_generated(i),m_custom(0) {}
    Wrapper(ImplCustom * i): m_generated(0),m_custom(i) {}
    int foo(int x,int y);
    void bar(double x);
    ....
private:
    ??? getImpl();
    ImplGenerated * m_generated;
    ImplCustom * m_custom;
};

int Wrapper::foo(int x,int y) {
    return getImpl()->foo(x,y);
}
void Wrapper::bar(double x) {
    getImpl()->bar(x);
}

是否可以编写一些C构造(类或任何其他,但不是宏)而不是getImpl()来解析当前的实现对象并调用相应的方法?
像这样:

???? getImpl() {
    return m_custom ? m_custom : m_generated;
}

注意:
只能应用对ImplCustom的更改(添加基类或make模板或其他内容),ImplGenerated是由外部项目自动生成的,因此无法更改(添加基类是不可能的).
包装器不能是模板,因为是接口类.

更新:
从ImplGenerated派生ImplCustom是不可能的.

解决方法

我在这里看到的解决方案是创建一个包装器

此解决方案的目标是为两个不相关的类生成一个接口.

让我们从制作Base classe开始:

struct ImplInterface {
    virtual int foo(int x,int y) = 0;
    virtual void bar(double x) = 0;
    // ...
};

现在,您可以为每个Impl创建包装器:

struct GeneratedWrapper : ImplInterface {
    virtual int foo(int x,int y) {
        _impl.foo(x,y);
    }

    virtual void bar(double x) {
        _impl.bar(x);
    }

private:
    ImplGenerated _impl;
};

struct CustomWrapper : ImplInterface {
    virtual int foo(int x,y);
    }

    virtual void bar(double x) {
        _impl.bar(x);
    }

private:
    ImplCustom _impl;
};

现在您可以像这样使用这些包装器:

ImplInterface* wrapper = new GeneratedWrapper(implGenerated);

使用模板可以缩短这个方法,让我们为你的新界面制作一个包装器:

template<typename T>
struct EveryImplWrapper : ImplInterface {
    virtual int foo(int x,y);
    }

    virtual void bar(double x) {
        _impl.bar(x);
    }

private:
    T _impl;
};

现在您可以像这样使用它:

ImplInterface* = new EveryImplWrapper<ImplCustom>(implCustom);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读