Consider the following scenario:
template <bool expensive>
constexpr auto computeValue() {
// ...
}
void funcA() {
static constexpr auto value_a = computeValue<false>(); // should be at compile time
// ...
}
void funcB() {
static const auto value_b = computeValue<true>(); // should be at runtime
// ...
}
In my scenario computeValue<true>
is an expensive computation and is unable to be evaluated at compile time due to an out of memory error on my system. However, it is able to be run in an acceptable amount of time at runtime, with the same computer. computeValue<false>
does not have this problem, which is why it is computed at compile time in funcA
.
The problem is that the compiler still tries to evalute computeValue<true>()
at compile time despite the fact that I left out the constexpr
, and subsequently runs out of memory. Is there a way to force it to leave this computation for runtime evaluation?
CodePudding user response:
const int
might be "promoted" to constexpr int
if initializer is constexpr
.
Dropping const
would make disallow the constexpr
(compiler might still decide to optimize and does some computation at compile time, but result would be unusable in constant expression):
void funcB()
{
static auto init_value_b = computeValue<true>();
static const auto value_b = init_value_b; // That const cannot be constexpr
// ...
}
CodePudding user response:
The only solution I could figure out was to make a second copy of the function except without the constexpr
.
template <bool expensive>
constexpr auto computeValue() {
// ...
}
template <bool expensive>
auto computeValueRuntime() {
return computeValue<expensive>();
}
void funcB() {
static const auto value_b = computeValueRuntime<true>(); // should be (and is) at runtime
// ...
}
This seems pretty inelegant though, so I'm wondering if there's some syntactic way of doing it.