0

I've been trying to find an Adapter solution in C++ to two external interfaces, which are so similar but differs in return types in enumerations.

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();
}

Do you have any idea about a solution so I can use a wrapper to call either interface A or B?

ReturnType? MyAdapter::Method()
{
// Call Method from A or B but how
}

Regards, Burak

Note Added: I've solved the problem using Boost.Variant

4

2 に答える 2

0

独自の戻り値を持つ 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();
于 2013-02-18T10:38:07.273 に答える
0

私の知る限り、変数の戻り値の型を持つ関数を書くことはできません。したがって、次のようなものをお勧めします。

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;
}
于 2013-02-18T09:49:51.383 に答える