【发布时间】:2020-11-30 03:25:26
【问题描述】:
在一个简单的嵌入式平台上,我没有可用的 RTTI,但我想使用 C++ 的优势,例如继承类层次结构,如提供的示例。目前我正在使用以下代码来模拟动态演员。为了简化这个讨论,我将代码移植到一个简单的 main.cpp。我使用 mingw 编译器来测试我的示例。代码按预期工作,但接缝并不理想。我不是在寻找考虑所有方面的通用动态演员替换解决方案。有什么方法可以更轻松地实现这个演员表吗?
class I_BC
{
public:
virtual ~I_BC() {}
virtual int getI_BC() = 0;
};
class I_C
{
public:
virtual ~I_C() {}
virtual int getI_C() = 0;
};
class A
{
public:
virtual ~A() {}
int xx() {return 1;}
template <typename T>
T* cast() { return nullptr;}
protected:
virtual I_BC* cast2BC() {return nullptr;}
virtual I_C* cast2C() {return nullptr;}
};
template <>
I_BC* A::cast<I_BC>() {return this->cast2BC();}
template <>
I_C* A::cast<I_C>() {return this->cast2C();}
class B : public A, public I_BC
{
public:
int getI_BC() override { return 0xB000000C;}
int bar() {return 2;}
protected:
I_BC* cast2BC() override {return this;}
};
class C : public A, public I_BC, public I_C
{
public:
int foo() {return 3;}
int getI_C() override { return 0xC000000C;}
int getI_BC() override { return 0xC00000BC;}
protected:
I_BC* cast2BC() override {return this;}
I_C* cast2C() override {return this;}
};
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
A* a = new B();
// Ok I know that B implement I_BC interface so cast it now
I_BC* bc = a->cast<I_BC>();
cout << "Res : 0x" << hex << bc->getI_BC() << endl;
}
【问题讨论】:
-
如果虚拟方法有效,
dynamic_cast也有效。 -
好的,我禁用了 -rtti,但我在固件中经常使用虚拟方法。我对这个话题的了解是基于这个网页:arobenko.gitbooks.io/bare_metal_cpp/content/compiler_output/…
-
Herb Sutter 在CppCon 2019 上的演讲(部分)谈到了 C++ 的指导性零抽象开销 原则,并通过仅在使用 RTTI 时才付费来使 RTTI“更便宜” - 并且只有涉及的部分。今天可能无法为您提供帮助,但当此功能可用时,您将对这一发展非常感兴趣(我敢打赌)。
-
@JonnySchubert 哦,我错了,你是对的,对不起。 Virtuals 可以在没有 RTTI 的情况下工作,但动态投射不会 link。