venkysmarty
venkysmarty

Reputation: 11441

about before function in typeinfo

I am reading modern C++ design. Following is the text snippet taken from typeinfo description.

The before member function introduces an ordering relationship for type_info objects. Using type_info::before, you can perform indexing on type_info objects.

If you want to sort type_info objects, again you must actually store pointers to type_info, and this time you must use the before member function. Consequently, if you want to use STL's ordered containers with type_info, you must write a little functor and deal with pointers.

In above description, what is meant by indexing on type_info objects and how can we achieve this using "before" function.

Also another question is what does author mean if we want to use STL containers with type_info, we must write a little functor and deal with pointers.

Thanks!

Upvotes: 2

Views: 629

Answers (3)

Bo Persson
Bo Persson

Reputation: 92371

The thing is that you don't know if you get the same type_info object each time or if there are several objects referring to the same type. Therefore you cannot just compare the type_ info objects themselves.

The before() function must sort this out, in an implementation specific way, and return a proper ordering.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361722

what does author mean if we want to use STL containers with type_info, we must write a little functor and deal with pointers.

That part means when using STL ordered containers, you have to tell the container how to sort the elements it contains, and for that you've to write a functor that would use type_info::before internally to do the comparison between type_info pointers.

Ordered container requires sorting, sorting requires comparison, comparison requires you to write a comparer that is either a function or functor. Simple!

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254721

"Indexing" here means using it as the key in an ordered container, such as std::set or std::map. These require a comparison functor to order the keys. You'll also need to use pointers to type_info, rather than the objects themselves, since they are not copyable. It could be achieved like this:

struct type_info_before
{
    bool operator()(std::type_info const * a, std::type_info const * b)
    {
        return a->before(*b);
    }
};

typedef std::set<std::type_info const *, type_info_before> type_info_set;

Or, as is described in the book, you could wrap the pointer in a little class and overload the comparison operators for that.

Upvotes: 0

Related Questions