Search code examples
c++booleanconditional-operatorfunction-definition

How to program a function whose return value is depending on the flag without using "if"?


I want to make a class function like the conceptual code below.

double function(){
  if(flag==true){
    "some process and return "
  } 
  else{
    "another process and return"
  }
}

where flag is the boolean member of the class. I want to make this function without using if because I use this function many times. The points are

  1. I want to use the same function with the two cases of the process.
  2. I want to avoid re-evaluation of a flag that doesn't change its value for some period.

Solution

  • If you want to call one of two different member functions depending on the value of a bool without using an if or something else that might lead to branching, you could create a table containing two function pointers and use that for lookup by using the bool for indexing. If you only want to do this lookup when the value of the flag changes, you could store a pointer to the active function and only do the lookup when flag is set.

    Example where the member functions are also taking an argument:

    #include <iostream>
    
    class foo {
    public:
        using func_t = double(foo::*)(double); // the type of the member functions
    
        double some(double x) { return x * 3.14159; }
        double another(double x) { return x * 3.14159 * 3.14159; }
    
        double function(double x) {      
            return (this->*active)(x); // "active" only changes when "flag" is set
        }
    
        void set(bool x) {
            flag = x;
            // lookup without "if" to set the active function:
            active = funcs[flag];
        }
    
    private:
        // a static table of the functions to be called - only initialized once
        static constexpr func_t funcs[]{&foo::some, &foo::another};
    
        bool flag = false;
        func_t active = &foo::some;     // the active function
    };
    
    int main() {
        foo x;
    
        x.set(false);
        std::cout << x.function(2.) << '\n';
    
        x.set(true);
        std::cout << x.function(3.) << '\n';    
    }
    

    Output

    6.28318
    29.6088