bsobaid
bsobaid

Reputation: 975

c++ code refactoring using function objects

I have some functionality that returns a value based on values that are set once at start up (in constructor). As these conditional value are only set once, I dont want to be checking them all the time. Is there a way to do the if-check only once and then dont do it again and again using function objects or some other mechanism?

class MyValue {
    bool myVal; //set only once in the constructor
    int myval1; //often updates
    int myval2; //often updates


    myValue(bool val, int val1, int val2)
    {
        myVal = val; // only place where myVal is set

        // this value changes often in other functions not shown here
        myval1 = val1;

        // this value changes often in other functions not shown here
        myval2 = val2;
    }

    int GetMyValue() //often called
    {
        if(myval)    /* Is there a way I dont have to do an if check here? 
                        and simply write a return statement? */
            return myval1;

        return myval2;
    }    
};

Upvotes: 1

Views: 74

Answers (2)

MiMo
MiMo

Reputation: 11983

Use a pointer:

class MyValue
{
   int* myVal;
   int myval1; //often updates
   int myval2; //often updates

  myValue(bool val, int val1, int val2)
  {
     if (val) { 
         myVal = &myval1; 
     } else { 
         myVal = &myval2 
     }
     myval1 = val1;
     myval2 = val2;
  }

  int GetMyValue() //often called
  {
     return *myval;
  }

};

(or even better a reference as in Rabbid76 answer)

Upvotes: 1

Rabbid76
Rabbid76

Reputation: 211277

Use a member which is either a reference to myval1 or to myval2, the referenc has to be initialized once in the constructor:

class MyValue
{
    bool myVal; //set only once in the constructor
    int myval1; //often updates
    int myval2; //often updates
    int &valref;

public:
    MyValue( bool val, int val1, int val2 )
        : myVal( val )
        , myval1( val1 )
        , myval2( val2 )
        , valref( val ? myval1 : myval2 )
    {}

    int GetMyVal() { return valref; }
};

Upvotes: 1

Related Questions