mardi 20 avril 2021

Compile time if else in c++ 11

I have this template function -

template <int N> 
void foo() {
  if (N < 2) {
    bar1();
  } else {
    bar2();
  }
}

I want to deduce if else during compile time in C++11 to make the function efficient. I thought of adding an additional template bool variable like this -

template <int N, bool I = (N < 2), std::enable_if<I>> 
void foo() {
    bar1();
}
template <int N, bool I = (N < 2), std::enable_if<!I>> 
void foo() {
    bar2();
}

Not sure if this is the right approach. Can anyone please help?

Aucun commentaire:

Enregistrer un commentaire