What is `type_info::before` useful for?

只谈情不闲聊 提交于 2019-11-30 11:40:03

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";
}

This is useful to define an order on typeinfo objects, e.g. to put them into a std::map. The obvious follow-up question is: why isn't it spelled operator<()? I don't know the answer to this question.

It gives an ordering.

That is required if you want to store values in some containers, like std::map.

Think of it as less-than (<) operator for type_info objects. If you ever wanted to store in ordered collection - such a set of map - you can use it to make an appropriate comparator. It's a reliable and preferred way, as opposed to, say, using type's name which might not be unique.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!