c++initializationconstexpr

Switch constexpr member initialization depending on bool template parameter


Is there a way to switch member variable initalization based on a template parameter?

Some enable_if trick or something similar?

I could do something like this with a lambda call

template<bool A>
struct Test{

  static constexpr int a = [](){
    if constexpr(A) return 1; else return 2;}();

};

but this fails for my actual use case with a look up array (also tried with std:array)

template<bool A>
struct Test{
  // A==true variant
  static constexpr std::int8_t table[4] {1,2,3,4};
  // A==false variant
  //static constexpr std::int8_t table[4] {4,6,7,3};

Solution

  • You can indeed use a lambda that will return a std::array according to the value of A

    #include <array>
    #include <cstdint>
    
    template<bool A>
    struct Test {
      static constexpr auto table = [] {
          if (A)  { return std::array<std::int8_t,4> {1,2,3,4}; }
          else    { return std::array<std::int8_t,4> {4,6,7,3}; }
      }();
    };
    
    static_assert (Test<true> ::table == std::array<std::int8_t,4> {1,2,3,4});
    static_assert (Test<false>::table == std::array<std::int8_t,4> {4,6,7,3});
    
    int main() {}
    

    Demo