Implementing comparators with tuple

C++11 introduces the interesting std::tuple feature.
Here, I will present the usage of std::tie to implement comparison operators in a class.

Let’s say we have to implement operator== in a class that consists in comparing every member of that class. Here is a typical implementation:

It is possible to implement the operator== using the new standard function std::tie as follows:

With the future C++14 standard, it will be possible to avoid code repetition:

In the meantime, we can approach this writing in C++11:

The same can be applied for other comparison operators

The introduction of orderable() is because the order of members in tie is important for the less operator. Usually tied() can be rerouted on orderable().

This entry was posted in C++, C++11. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *