Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making all mathematical operators of a struct manipulate the same member

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;}
    ...
}
like image 514
user1521896 Avatar asked Jun 16 '14 14:06

user1521896


People also ask

Do all mathematical operators have the same precedence?

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.

What are the 6 mathematical operators?

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.


1 Answers

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.

like image 113
Fred Foo Avatar answered Nov 11 '22 15:11

Fred Foo