1

I need to calculate the initial guess for the newtons method at compile-time. I'd like to prevent this calculation from happening at runtime.

Usually, I'd solve this problem using the enum trick:

enum
{
  a = make_coeff(...),
  b = make_coeff(...),
  c = make_coeff(...)
};

where a, b, c are coefficients and make_coeff() is a consteval/constexpr function. I can't use this approach this time, because the coefficients are of class type.

I have tried:

static constexpr coeff_type a[]{make_coeff(...), make_coeff(...), make_coeff(...)};

Would such an array of coefficients guarantee that make_coeff() will not be executed at runtime? Even though make_coeff() is marked consteval, gcc will happily generate code for it. But clang will not allow even a static constexpr array.

the errors clang gives are:

error: static variable not permitted in a constexpr function
error: cannot take address of consteval function 'make_coeff' outside of an immediate invocation

gcc is happy, but I am suspicious of what it is actually doing.

another thing I was thinking about is:

template <auto C>
constexpr auto coeff() noexcept
{
  return C;
}

coeff<make_coeff(...)>();

since I can pass a coefficient as a non-type template parameter.

is a template array possible?

template <auto ...C>
decltype((C, ...)) const a[]{C...};

perhaps even something like:

template <std::size_t I, auto ...C>
auto get() noexcept
{
  // ... easy to implement, but I'm not sure if it is worthwhile
}
user1095108
  • 14,119
  • 9
  • 58
  • 116
  • Making the variable constexpr forces its initialization to occur at compile-time. If Clang doesn't like consteval, try a constexpr function. – HolyBlackCat Dec 23 '22 at 04:08
  • I'm not so sure, I think there's some leeway given to the compiler as to what to do. This is why I prefer the enum trick whenever I can use it. – user1095108 Dec 23 '22 at 04:15
  • Perhaps the standard says so, but I don't think I've seen compilers behave otherwise. You can always check the result on https://gcc.godbolt.org to be sure. – HolyBlackCat Dec 23 '22 at 04:16
  • 1
    The standard doesn't guarantee anything anything at all to happen at compile time. It doesn't guarantee there is a compiler to begin with. – n. m. could be an AI Dec 23 '22 at 06:03
  • If you can create a boolean expression with one or more coefficients, you could put it in a `static_assert` and have a compile time error if it's not evaluated at compile time. – MatG Dec 23 '22 at 13:10
  • @n.m true, it allows an interpreter, hence everything would be forced to happen at runtime. – user1095108 Dec 23 '22 at 14:25

0 Answers0