c++ - 如何从 type_info 获取模板参数的类型

标签 c++ templates c++11 rtti

我有一棵树,其中每个节点基本上是这样的:

struct node
{
    std::unordered_set<object*> objects;
    std::map<std::type_index,node> children;
};

当我遍历树以添加新类型时,我想做一个检查:

std::is_base_of<base,derived>

但是,我拥有的关于派生类型的唯一信息是 type_index/type_info*

我是否可以将 type_info* 转换为 template 参数?

如果没有,我的其他选择是什么?我想可以调用 decltype(*objects.begin()),但这需要每个节点中的每个集合永远不会为空。

最佳答案

Is there anyway i can transform the type_info* to a template argument?

不,没有办法。模板是编译时的东西,RTTI 是运行时的。两者之间没有联系。

I guess could call decltype(*objects.begin()), but that would require each set in every node to never be empty.

不需要那样做。 decltype 不计算它的参数——它不需要。它只需要检查类型。您可以在不调用 UB 的情况下愉快地执行 decltype(*a_null_pointer),因为永远不会对表达式求值 - 这就是所谓的未求值上下文sizeof 属于同一类别。

请注意,虽然这对您没有多大帮助 - 您只会得到 object*& 。如果不先准备映射,通常无法从运行时信息中获取类型。

关于c++ - 如何从 type_info 获取模板参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832679/

相关文章:

c++ - 使用表达式模板编译时间数组索引——constexpr?

C++ 异常:内存位置 0x003DF4C0 处的 std::out_of_range

c++ - 这条线是如何打印数组的?

c++ - 画出这个形状

c++ - 这些是 std::enable_if 的预期错误,还是我使用不当?

c++ - 使用 Boost::odeint 和 Eigen::Matrix 作为状态 vector

php - 如何消除 Smarty {block} 中的空格?

c++ - 编译器在数组到指针衰减存储中生成的指针存储在哪里?

c++ - 检测内存页面大小

c++ - 有没有办法限制进程的输出文件数量?