Martin
Martin

Reputation: 9369

Guessing the type from a reference

I have the following structures, where some of them are defined in a framework and some others are not, as indicated in the comments:

struct FixedInterface { // from the framework
   virtual ~FixedInterface() {}
}

struct MyAdditionalInterface { // generic, personal/additional interface
};

The following structures in my program can derive from the above two structures and are used/passed to the strongly-typed framework

struct MyFirstInterface : MyAdditionalInterface, FixedInterface {
};

struct MySecondInterface : FixedInterface {
};

struct MyThirdInterface : MyAdditionalInterface, FixedInterface {
};

// ...

struct MyNthInterface : FixedInterface {
};

Now the framework let me define and "inject" a custom function having the following signature. This function is called by the framework when needed:

void MyClass::my_function(const FixedInterface& obj) {
}

In the body of the above function I need a way to know if obj is an instance of MyAdditionalInterface (that is MyFirstInterface or MyThirdInterface) so that I can cast the obj to use the MyAdditionalInterface.

How could I obtain that information? I am free to modify my structures, as long as I do not change the hierarchy and MyAdditionalInterface does not have vtable's (no virtual functions or destructors, the reason is the the framework would not allow me that).

I am free to use Boost in case. I have access to C++11.

Upvotes: 0

Views: 361

Answers (1)

Alex Chamberlain
Alex Chamberlain

Reputation: 4207

A dynamic_cast will work;

MyAdditionalInterface obj2 = dynamic_cast<MyAdditionalInterface const&>(obj)

It will throw an exception is obj is not a MyAdditionalInterface.

However, the use of dynamic_cast indicates you should redesign your hierarchy.

One possible solution (1)

It appears you only use MyAdditionalInterface on top of a FixedInterface?

If so,

struct MyAdditionalInterface : FixedInterface { ... }

Then, define 2 overloads.

void MyClass::my_function(const FixedInterface& obj) {
}
void MyClass::my_function(const MyAdditionalInterface& obj) {
}

One possible solution (2)

For example, let us define

struct MyConvolutedInterface : MyAdditionalInterface, FixedInterface {
    ...
}

then redefine the classes as follows

struct MyFirstInterface : MyConvolutedInterface  {
};

struct MySecondInterface : FixedInterface {
};

struct MyThirdInterface : MyConvolutedInterface  {
};

// ...

struct MyNthInterface : FixedInterface {
};

Then, define 2 overloads

void MyClass::my_function(const FixedInterface& obj) {
}
void MyClass::my_function(const MyConvolutedInterface& obj) {
}

I'm skeptical as to whether this would be the best solution in many cases, however.

Upvotes: 1

Related Questions