(Note: tuple and tie can be taken from Boost or C ++ 11.)
When writing small structures with two elements, I sometimes prefer to choose std::pair , because everything necessary is already done for this data type, for example, operator< for strict-weak order.
Disadvantages, although they are rather useless variable names. Even if I myself created this typedef , I won’t remember in 2 days that the first and the second accurate, especially if they are both of the same type. This gets even worse for more than two participants, as the pair attachment sucks in pretty much.
Another option for this is tuple , either from Boost or C ++ 11, but in reality it does not look better and clearer. Therefore, I return to writing the structures themselves, including any necessary comparison operators.
Since especially operator< can be rather cumbersome, I was thinking about getting around this whole mess by simply relying on the operations defined for tuple :
An operator< example, for example. for strictly weak ordering:
bool operator<(MyStruct const& lhs, MyStruct const& rhs){ return std::tie(lhs.one_member, lhs.another, lhs.yet_more) < std::tie(rhs.one_member, rhs.another, rhs.yet_more); }
( tie makes a tuple T& links from the arguments passed.)
Change The suggestion from @DeadMG for personal inheritance from tuple not bad, but it has some disadvantages:
- If the operators are free (maybe friends), I need to inherit in public
- With casting, my functions / operators (
operator= in particular) can be easily circumvented - With
tie solution, I can leave some members if they are not relevant for ordering
Are there any flaws in this implementation that I need to consider?
c ++ operators c ++ 11 tuples
Xeo Jun 02 '11 at 18:36 2011-06-02 18:36
source share