Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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};
like image 885
vlad_tepesch Avatar asked Jul 29 '26 01:07

vlad_tepesch


1 Answers

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

like image 180
abcdefg Avatar answered Jul 31 '26 16:07

abcdefg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!