I expected that the compiler could generate a set of results for the sine and output them without having to calculate Taylor. Instead, the generated code executes a sine, as if it were any other function other than constexpr.
For the constexpr function, which must be evaluated at compile time, the following should apply:
- All its input arguments must be constant expressions.
- Its result should be used in constant expression.
Assignment in a test for loop is not a constant expression. Therefore, sine cannot be evaluated at compile time.
What you really need is to statically initialize the elements of the array with sine() . Using std::array and some helper mechanisms, this can be done as shown below:
#define r 0.01745329251 constexpr double factorial(int n) { double res = 1.0; for(int i(2); i <= n; ++i) res *= i; return res; } template<typename T> constexpr T power(T &&base, int const n) { if(!n) return 0.0; T res = base; for(int i(1); i < n; ++i) res *= base; return res; } template <typename T, int N = 5> constexpr T sine(T &&x) { T res = x * r; for (int i(3), sgn(-1); i <= N; i += 2, sgn = -sgn) { res += power(x * r, i) / factorial(i); } return res; } template <class T, std::size_t N, std::size_t... Is> constexpr std::array<T, N> sine_array_impl(std::index_sequence<Is...>) { return {{sine(T{Is})...}}; } template <class T, std::size_t N> constexpr std::array<T, N> sine_array() { return sine_array_impl<T, N>(std::make_index_sequence<N>{}); }
Live demo
source share