C++适配器-用于名称相同但返回类型不同的方法

C++ Adapter - For Methods With Same Name But Different Return Type

本文关键字:返回类型 方法 适配器 用于 C++      更新时间:2023-10-16

我一直在尝试在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();