从引用中猜测类型

Guessing the type from a reference

本文关键字:类型 引用      更新时间:2023-10-16

我有以下结构,其中一些是在框架中定义的,而另一些不是,如注释所示:

struct FixedInterface { // from the framework
   virtual ~FixedInterface() {}
}
struct MyAdditionalInterface { // generic, personal/additional interface
};

我的程序中的以下结构可以从上面两个结构派生出来,并被使用/传递给强类型框架

struct MyFirstInterface : MyAdditionalInterface, FixedInterface {
};
struct MySecondInterface : FixedInterface {
};
struct MyThirdInterface : MyAdditionalInterface, FixedInterface {
};
// ...
struct MyNthInterface : FixedInterface {
};

现在框架允许我定义并"注入"一个具有以下签名的自定义函数。该函数在需要时由框架调用:

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

在上述函数的主体中,我需要一种方法来知道obj是否是MyAdditionalInterface的实例(即MyFirstInterfaceMyThirdInterface),以便我可以转换对象以使用MyAdditionalInterface

我怎样才能得到那个信息?我可以自由地修改我的结构,只要我不改变层次结构,MyAdditionalInterface没有虚函数(没有虚函数或析构函数,原因是框架不允许我这样做)。

我可以自由使用Boost以防万一。我可以访问c++ 11

dynamic_cast可以;

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

如果obj不是MyAdditionalInterface,则抛出异常。

但是,使用dynamic_cast表明您应该重新设计您的层次结构。

一个可能的解(1)

似乎你只在FixedInterface之上使用MyAdditionalInterface ?

如果是这样的话,

struct MyAdditionalInterface : FixedInterface { ... }

然后定义2个重载。

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

一个可能的解(2)

例如,让我们定义

struct MyConvolutedInterface : MyAdditionalInterface, FixedInterface {
    ...
}

然后按如下方式重新定义类

struct MyFirstInterface : MyConvolutedInterface  {
};
struct MySecondInterface : FixedInterface {
};
struct MyThirdInterface : MyConvolutedInterface  {
};
// ...
struct MyNthInterface : FixedInterface {
};

然后定义2个重载

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

我怀疑在许多情况下这是否是最好的解决方案。