s hukahi
s hukahi

Reputation: 29

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.

Upvotes: 1

Views: 468

Answers (3)

infinitezero
infinitezero

Reputation: 2077

You can just cast the boolean into an int

int test(bool flag)
{
    return static_cast<int>(flag);
}

int not_test(bool flag)
{
    return static_cast<int>(!flag);
}

Remark: By the time this answer was posted, the question was completely different.

Upvotes: -1

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

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

Upvotes: 4

MSalters
MSalters

Reputation: 179907

Class function, flag, and two different behaviors? You probably should make two derived classes, drop the flag, and use a virtual function instead.

Upvotes: 2

Related Questions