3

This relates to a problem I'm trying to solve which has already been addressed a couple of times Lookup table with constexpr; constexpr array and std::initializer_list

I have a constexpr function that's too slow to use a run time, for my purposes I want to use a lookup table, and ideally I want to use the same function at run time 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 that it's actually valid (it doesn't feel constexpr). Have I strayed into undefined behaviour somehow?

Community
  • 1
  • 1
Tim
  • 693
  • 3
  • 11

0 Answers0