【问题标题】:Simulate dynamic cast without RTTI模拟没有 RTTI 的动态投射
【发布时间】: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

标签: c++ casting rtti


【解决方案1】:

这是一个使用宏来减少样板代码的自定义 RTTI 实现: https://www.axelmenzel.de/articles/rtti

【讨论】:

  • 感谢分享,但由于安全政策限制,我无法打开网站。
  • 我在这样的工作中遇到了奇怪的安全问题。当一个非恶意网站由于某种奇怪的原因被标记时,这可能会令人沮丧。有了那个链接,只有答案是不受欢迎的。
  • 就目前而言,这个答案应该是评论。即使它有帮助并解决了 OP 的问题。
  • 在 StackOverflow 上不赞成仅链接的答案。链接会随着时间而中断。请直接在答案中包含相关代码。
猜你喜欢
  • 2020-07-07
  • 2012-05-14
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 2014-11-16
  • 2019-09-01
相关资源
最近更新 更多