Is it possible to create a type (let’s say degrees) and define specific operators for it? Such as: =, +, *, -, /, +=, *=, -=, /=.
I’m wondering this because I need to use degrees for one of my programs and I don’t want to use a float object because using degrees a; a.value = 120; a.value = b.value + a.value; is redundant over a simple degrees a = 120; a = b+a;.
Now why don’t I just use:
typedef float degrees;
? Well, because I need one more thing. When I write
degrees a;
a = 120;
a += 300;
a should be equal to 60 (420-360) because I don’t really need a = 6150 when I can have a = 30 with the same effect. So I’d overload those operators to keep the value between 0 and 360.
Is it possible? And, if so, how?
The solution to your problem doesn’t need Boost or any other libraries. You can achieve what you want by using C++ classes, and overloading both the mathematical operators you want (+, -, *, /, etc) and the assignment operators you want (=, +=, -=, etc) and the comparison operators you want (<, >, <=, >=, etc)… or really any operators you want!
For example:
Then you can do things like this:
I’ve given you an example for overloading assignment and plus operators, but you can try this same thing with any other kind, and it should work.