我有一棵树,其中每个节点基本上是这样的:
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/