gpt4 book ai didi

c++ - 从引用猜测类型

转载 作者:行者123 更新时间:2023-11-28 07:43:14 25 4
gpt4 key购买 nike

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

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 {
};

现在框架让我定义并“注入(inject)”具有以下签名的自定义函数。该函数在需要时由框架调用:

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

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

我如何获得该信息?我可以自由修改我的结构,只要我不更改层次结构并且 MyAdditionalInterface 没有 vtable(没有虚函数或析构函数,原因是框架不允许我这样做)。

我可以免费使用 Boost 以防万一。我可以访问 C++11。

最佳答案

dynamic_cast 将起作用;

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

obj 不是 MyAdditionalInterface 时会抛出异常。

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

一种可能的解决方案(一)

看来您只在 FixedInterface 上使用了 MyAdditionalInterface

如果是,

struct MyAdditionalInterface : FixedInterface { ... }

然后,定义 2 个重载。

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

一种可能的解决方案(二)

例如,让我们定义

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) {
}

不过,在许多情况下,我怀疑这是否是最佳解决方案。

关于c++ - 从引用猜测类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15405625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com