I have a class with an attribute of type std::string. I’d like to provide some comparison operator functions like <, >, ==, <=, and >= for the class by comparing the attribute.
My questions is that: any easy way or tool to
(1) just write one or two functions, such as the one for operator < (and ==), others can be automatically generated.
(2) or even simpler since the class comparison is depending on its attribute of type std::string whose comparison functions are already provided.
Curiously recurring template pattern
In this case you provide a simple base class which implements all needed operators and simply inherit from it:
This doesn’t share the drawbacks from
std::rel_ops(see below). However, you still need to implementoperator<andoperator==. A similar trick is used byboost.C++20’s
<=>might improve the situation further (see below).std::rel_ops(deprecated in C++20)std::rel_opsprovides the additional operations based on<an==, so you just need to write two operators.However, it will be deprecated in C++20, where
a <=> bwill get thrown into the mix.Requirements
You just need the equality (
operator=) and the lesser than (operator<) comparison operator. The rest can be generated automatically withstd::rel_ops, since the following holds:Note that these are less efficient than writing those by hand.
Warning
However, since it’s easy to provide those operators yourself you should just take the extra effort and write them. And they also have some drawbacks, as mentioned by R. Martinho Fernandes: