从引用中猜测类型
Guessing the type from a reference
我有以下结构,其中一些是在框架中定义的,而另一些不是,如注释所示:
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
或MyThirdInterface
),以便我可以转换对象以使用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) {
}
我怀疑在许多情况下这是否是最好的解决方案。
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将成员函数的返回类型引用到C++中的自定义类
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- C++:类类型引用运算符=用法
- 将 const 类型引用对象注册为类成员对象C++
- 错误:绑定到类型引用会丢弃限定符
- 如果作为基类型引用传递,派生类型会解构吗
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 类型引用的初始化无效
- C++ 从函数返回多个类型引用并将它们强制转换为我们需要的类型
- 函数常量返回类型:类型引用的初始化无效
- 将类型的嵌套类型引用为类模板的参数的问题
- 与返回类型(引用、常量引用)混淆
- 调用具有const键类型引用的std::指针集的count方法
- 返回运算符类型=-引用或值
- 非类型引用形参/实参
- c++中定义不同类型引用的区别
- 为什么返回类型引用输出流
- 非类型(引用)模板参数和链接
- 类型引用的初始化无效