Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从引用猜测类型_C++_Boost_C++11 - Fatal编程技术网

C++ 从引用猜测类型

C++ 从引用猜测类型,c++,boost,c++11,C++,Boost,C++11,我有以下结构,其中一些是在框架中定义的,另一些不是,如评论所示: struct FixedInterface { // from the framework virtual ~FixedInterface() {} } struct MyAdditionalInterface { // generic, personal/additional interface }; 我的程序中的以下结构可以从上述两种结构派生,并用于/传递给强类型框架 struct MyFirstInterface

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

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
(即
MyFirstInterface
MyTirdInterface
)的实例,以便我可以强制转换obj以使用
MyAdditionalInterface

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


我可以自由使用
Boost
以防万一。我可以使用C++11。

A
dynamic\u cast
可以工作

MyAdditionalInterface obj2 = dynamic_cast<MyAdditionalInterface const&>(obj)
然后,定义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) {
}

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

为什么需要将其转换为
MyAdditionalInterface
?动态转换很好,我起初没有尝试,因为出于某些原因,我认为MyAdditionalInterface(除了FixedInterface)是最好的必须有一个vtable/type信息才能使dynamic_cast正常工作。我必须更好地阅读关于动态演员的std。重载是可以的,但是框架比我描述的要复杂一点,并且没有重载(无论如何thx)@Martin
dynamic\u cast
s是一个非常糟糕的主意,而且相当昂贵。通常应避免这些情况。重载应该起作用,所以如果它们不起作用,我会问另一个问题来说明这种影响。
void MyClass::my_function(const FixedInterface& obj) {
}
void MyClass::my_function(const MyConvolutedInterface& obj) {
}