I have a question that may have been answered over 9000 times before but I really don't know how to word it, this is what I am going to try.
I've seen in some C++ books and tutorials that when defining your own class which has a iterable value (incrementable) semantics, you can overload operator++
for it (all I'm going t state here I'd guess applies for operator--
as well). The standard way of doing this seems to be:
class MyClass {
public:
MyClass& operator++ () {
increment_somehow();
return *this;
}
....
};
Where increment_somehow()
well... somehow increments the object's value.
Then, it is possible to define the postfix version of operator++
in a manner like this:
MyClass operator++ (MyClass& it, int dummy) {
MyClass copy(it);
++it;
return copy;
}
It is all fine and dandy (I think I got that idiom right), but the problem is that doing all that for each class that defines operator++
quickly becomes tiresome and verbose, so I was thinking that I could take some advantage of a trick that I recently learnt when overloading operators. That is, making use of the <utility>
header and a facility inside called rel_ops
that I found out about yesterday (I just came back to C++ after four years of being away...):
class MyClass {
public:
bool operator== (const MyClass& that) {
return compare_for_equality_somehow(that);
}
bool operator< (const MyClass& that) {
return compare_for_lessality_somehow(that);
}
....
using namespace std::rel_ops; // operators >, >=, <=, ! are "magically" defined!
};
(I just invented the term "lessality" for analogy purposes, my head refuses to come up with the correct mathematical term for some reason...)
I created a simple header <step_ops.hpp>
whose content somewhat imitates the std::rel_ops
namespace found in the Utility header. Fro what I can see after a couple of compiles, it just works(TM). Can I / Should I use this trick? What are possible pitfalls I could come up against if I create a class and use a using namespace MyLibrary::increment_operators
(for example)?
And maybe much, MUCH more important: Have I just reinvented the wheel again, or have I just created a useful small library that could be aggregated to such kinds of projects? Pretty much any experiments that I have tried to do with C++ to get myself back up-to-speed and collaborate stuff seem to already be covered under a boost::do_something
facility and it makes me kind of sad that I have spent so much time away.