C++适配器-用于名称相同但返回类型不同的方法
C++ Adapter - For Methods With Same Name But Different Return Type
我一直在尝试在C++中为两个外部接口找到一个Adapter解决方案,这两个接口非常相似,但在枚举中的返回类型不同。
enum
{
SAME_VALUE1,
SAME_VALUE2
} EnumTypeA
enum
{
SAME_VALUE1,
SAME_VALUE2,
DIFFERENT_VALUE3
} EnumTypeB
class A // not inherited
{
EnumTypeA Method();
}
class B // not inherited
{
EnumTypeB Method();
}
你对一个解决方案有什么想法吗?这样我就可以使用包装器来调用接口a或B了?
ReturnType? MyAdapter::Method()
{
// Call Method from A or B but how
}
谨致问候,Burak
注意:我已经用Boost解决了这个问题。变体
据我所知,不可能编写具有变量返回类型的函数。因此,我建议如下:
enum ReturnTypeEnum
{
ReturnTypeA,
ReturnTypeB
};
struct ReturnType
{
ReturnTypeEnum actualType;
union
{
EnumTypeA a;
EnumTypeB b;
}actualValue;
}
ReturnType MyAdapter::Method()
{
ReturnType retval;
//Call method from A or B, whichever necessary
//and construct retval accordingly.
return retval;
}
我会创建一个具有自己返回值的Adapter接口。
struct Adapter
{
virtual ~Adapter() {}
enum Enum {
VALUE1,
VALUE2,
VALUE3,
};
virtual Enum Method( ) = 0;
};
然后为A和B创建一个适配器。
struct AdapterA : public Adapter {
Enum Method( ) override { return Enum( a.Method() ); };
A a;
};
struct AdapterB : public Adapter {
Enum Method( ) override { return Enum( b.Method() ); };
B b;
};
这些很可能需要在单独的实现文件中,这样SAME_VALUE1
就不会在编译时发生冲突。然后您可以执行以下操作:
std::unique_ptr<Adapter> drv;
drv.reset( new AdapterA() );
drv->Method();
drv.reset( new AdapterB() );
drv->Method();
相关文章:
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 具有引用返回类型的重写方法上的协变返回类型无效
- Java 调用 dll 字符串返回类型方法
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 如何拥有两个名称相同但返回类型不同的纯虚拟方法
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 将返回类型推断为模板参数类型方法
- dlsym() 解决方法返回类型
- 我如何根据某些模板参数影响模板类方法的返回类型
- 访问方法的返回类型
- 更改基类方法在其派生类中的返回类型
- 具有协变返回类型的方法在 VC++ 上崩溃
- 如何检查模板类方法返回类型
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 解释C 中三种返回类型的方法
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 存储方法的返回类型和参数类型
- C 多重继承,虚拟方法覆盖问题和协变量返回类型