mardi 27 février 2018

Getting value of member depending on underlying object type

I have two structs - Foo1 and Foo2. Both have the same member called _b, but at different offsets.

struct FooBase { };

struct Foo1 : FooBase
{
    int _a = 2;
    int _b = 1;
};

struct Foo2 : FooBase
{
    int _b = 2;
};

struct Wrap
{
    Wrap(const FooBase& x) : _x(x) { }
    FooBase _x;
    int GetValue() { return /* MISSING */; }
};

I have a wrapper class called Wrap. I am looking for a way to return the value of _b without using virtual functions in the foo classes, since I can't change their size anymore.

Wrap x = Foo1();
int a = x.GetValue(); // should return 1

Wrap y = Foo2();
int b = y.GetValue(); // should return 2

Any ideas? I posted one approach in the comments but curious for a better solution.

Aucun commentaire:

Enregistrer un commentaire