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?

3
  • Why not use a static constexpr array? Commented May 12, 2015 at 11:14
  • 1
    Short answer is that it's a bit of a pain to get it working and the linker usually objects. This way seems quite elegant as it's only two lines of code. Commented May 13, 2015 at 6:58
  • I normally check constexpr with static_assert: static_assert(my_table::lookup(7) == 7); // your value Commented Feb 25, 2016 at 1:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.