gpt4 book ai didi

c++ - 将 RTTI 与普通旧结构 (gcc) 结合使用

转载 作者:行者123 更新时间:2023-11-28 02:09:17 24 4
gpt4 key购买 nike

我需要将某种 RTTI 信息“附加”到外部(不可修改)结构。

正如我从 gcc 实现中看到的那样,带有虚方法的结构在它们的开头还有一个指向与 type_info 相关的结构的指针。

因此,我需要通过使用具有两个部分的双指针来对这些外部结构进行操作:数据指针和“类型”指针。该双指针具有“正常”RTTI 结构的所有信息。你知道任何“合法的”或 hacky 的方式吗

最佳答案

为此创建一个智能指针类:

#include <typeindex>
#include <type_traits>

// minimal implementation
template<typename T>
class RTTIPointer
{
T* ptr_;
std::type_index type_;
public:
template<typename U, typename std::enable_if<std::is_convertible<U*, T*>::value>::type* = nullptr>
RTTIPointer(U* p) :
ptr_(p),
type_(typeid(*p))
{

}

// typename std::add_lvalue_reference<T>::type instead of T&
// to support void pointers
typename std::add_lvalue_reference<T>::type operator*() const
{
return *ptr_;
}

T* operator->() const
{
return ptr_;
}

T* get() const
{
return ptr_;
}

std::type_index type() const
{
return type_;
}
};

struct Base { int a; };
struct Derived : Base { int b; };

#include <iostream>

int main()
{
Derived b;
b.a = 2;
b.b = 3;
RTTIPointer<Base> r(&b);
std::cout << r->a << "\n" << r.type().name() << "\n";
RTTIPointer<void> q(&b);
std::cout << r.type().name() << "\n";
}

输出:

2
7Derived
7Derived

关于c++ - 将 RTTI 与普通旧结构 (gcc) 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321778/

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