【发布时间】:2015-10-28 13:35:19
【问题描述】:
我有两个具有相同接口方法的类:
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 的更改(添加基类或制作模板或其他),ImplGenerated 是由外部项目自动生成的,因此无法更改(添加基类是不可能的)。 Wrapper 不能是模板,因为是接口类。
更新: 从 ImplGenerated 派生 ImplCustom 是不可能的。
【问题讨论】:
-
能否从
ImplGenerated派生出ImplCustom? -
您不能在运行时更改函数的返回类型。选项是运行时多态 - 基类指针/引用和虚函数,或编译时多态 - 生成多个函数的模板。
标签: c++