I have a struct containing a double and several flags, but I would like to use it in my code as if it were just that double. Is there a way to simplify the following code so that all mathematical operators executed on an instance of this struct are executed on the containing double? My code runs but I suspect that C++ has a very elegant and short solution for my problem.
struct SomeStruct
{
double value;
bool someFlag;
bool someOtherFlag;
operator double(){return value;}
void operator=(double newValue){value = newValue;}
void operator+=(double valueToAdd){value += valueToAdd;}
void operator-=(double valueToSubtract){value-= valueToSubtract;}
void operator/=(double divisor){value /= divisor;}
void operator*=(double multiplier){value *= multiplier;}
double operator+(double valueToAdd){return value + valueToAdd;}
...
}
Arithmetic operators follow the same precedence rules as in mathematics, and these are: exponentiation is performed first (when available), multiplication and division are performed next, addition and subtraction are performed last.
The arithmetic operators for scalars in MATALB are: addition (+), subtraction (−), multiplication (*), division (/), and exponentiation (^). Vector and matrix calculations can also be organized in a simple way using these operators.
If you change the conversion operator to operator double &
, you get all the operators on double
for free, with the exception of operator=
:
#include <iostream>
struct Foo {
double d;
bool flag;
Foo() : d(0), flag(false) {}
operator double &() { return d; }
};
int main()
{
Foo x; // initialized to (0, false)
x.flag = true;
x += 1.1;
std::cout << x.d << " " << x.flag << std::endl;
x *= 2;
std::cout << x.d << " " << x.flag << std::endl;
}
prints
1.1 1
2.2 1
(second output is the flag
).
It may still be worthwhile to also define operator double() const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With