zontragon
zontragon

Reputation: 820

How to determine a functions` return value choosing possible options at compile time

I have two virtually identical function that receive same struct as parameter. A very simplified version of my functions like below:

struct Container {
 int A;
 int B;
}

int return_A_dependent(Container c){
  //... identical code for A and B ...
  int common_for_A_and_B = 0;
  return common_for_A_and_B + c.A;
}

int return_B_dependent(Container c){
  // ... identical code for A and B ...
  int common_for_A_and_B = 0;
  return common_for_A_and_B + c.B;
}

only difference between two functions is their return values that are depend on the structs' different variables. I want to combine these two functions without doing runtime check. Like passing a flag parameter and add a if statement to forward the return value like below:

int return_A_or_B(Container c, bool flag_A) {
 // ... identical code for A and B ...
  int common_for_A_and_B = 0;
  if (flag_A) {
    return common_for_A_and_B + c.A;
  }
  else {
    return common_for_A_and_B + c.B;
  }

How could I handle this at compile time without using "if"? Thanks in advance.

Upvotes: 2

Views: 173

Answers (1)

user7860670
user7860670

Reputation: 37599

template using pointer to member as a parameter (or just normal function with extra argument):

template<int Container::* p_member> int
Work(Container c)
{
    int common_for_A_and_B = 0;
    return common_for_A_and_B + c.*p_member;
}

Work<&Container::A>(c);

Upvotes: 2

Related Questions