Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template extract bool parameter

Tags:

c++

templates

I want to extract the bool value from template parameters, and use that value in somewhere else in the code. (More specifically, I want a if-else in compile time).

template<bool enable_xx>
struct A {
  void DoSomething() {
    if (enable_xx) {
      // do something 
    } else {
      // do something else
    }
  }

}

I'm using C++11, but if such feature exists for higher version C++ pls also tell me, thanks!

like image 557
Ziqi Liu Avatar asked Dec 07 '22 11:12

Ziqi Liu


1 Answers

C++17 provides a way to do this using if constexpr:

template<bool enable_xx>
struct A {
  void DoSomething() {
    if constexpr(enable_xx) {
      // do something 
    } else {
      // do something else
    }
  }
};

if constexpr only runs at compiletime, and it does exactly what you want.

like image 100
Alecto Irene Perez Avatar answered Dec 31 '22 13:12

Alecto Irene Perez