什么是`type_info :: before`有用? [英] What is `type_info::before` useful for?
问题描述
根据cplusplus.com, std :: type_info :: before()
function ...
According to cplusplus.com, the std::type_info::before()
function...
整理顺序只是一个特定实现保存的内部顺序,不一定与继承关系或声明顺序相关。
Returns true if the type precedes the type of rhs in the collation order.
The collation order is just an internal order kept by a particular implementation and is not necessarily related to inheritance relations or declaring order.
这对于什么有用?
推荐答案
考虑你想把 type_info
对象作为键放入 map< type_info *,value>
。 type_info
没有定义运算符<
,因此您必须提供自己的比较器。从 type_info
接口中保证工作的唯一的事情是 before()
函数,因为 type_info
或名称()
必须是唯一的:
Consider you want to put your type_info
objects as keys into a map<type_info*, value>
. The type_info
doesn't have an operator <
defined, so you must provide your own comparator. The only thing that is guaranteed to work from the type_info
interface is the before()
function, since neither the addresses of type_info
nor the name()
must be unique:
struct compare {
bool operator ()(const type_info* a, const type_info* b) const {
return a->before(*b);
}
};
std::map<const type_info*, std::string, compare> m;
void f() {
m[&typeid(int)] = "Hello world";
}
这篇关于什么是`type_info :: before`有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!