Std :: initializer_list in constexpr (lookup tables)

This refers to a problem I am trying to solve, which has already been covered a couple of times already. Look-up table with constexpr ; constexpr array and std :: initializer_list

I have a constexpr function too slow to use runtime, for my purposes I want to use a lookup table and ideally I want to use the same function at runtime and compile time.

I came up with this

template<template<size_t>class f, size_t... values>
struct lookup_table{

  static constexpr auto lookup(size_t i){

    auto my_table = {f<values>::value...};
    return *(my_table.begin() + i);

  }

};



template<size_t n>
class some_function{

  // this is a terrible way to calculate an exponential
  static constexpr auto slow_exponential(size_t x){
    double y = 1 + ((double)x / 1000000.0);
    double retval = 1;
    for (int i = 0; i < 1000000; i++)
      retval *= y;
    return retval;
  }
public:
  static constexpr double value = slow_exponential(n);
};

int main(int, char**){



  using my_table = lookup_table<some_function, 0,1,2,3,4,5,6,7,8,9>;

  // test for constexprness
  constexpr int x =  my_table::lookup(7);
  using X = std::integral_constant<int, x>;

  std::cout << "enter n" << std::endl;
  int n;
  std::cin >> n;
  std::cout << "exp(" << n << ") = " << my_table::lookup(n) << std::endl;
  std::cout << "exp(" << n << ") = " << std::exp(n) << std::endl;

  return 0;

}

      

This compiles and works as expected with Clang 3.5, but I'm not 100% sure if it's actually valid (it doesn't feel constexpr). Am I deviating from undefined behavior in some way?

+3


source to share





All Articles