A few days ago I asked by which criteria the compiler decides whether or not, to compute a constexpr function during compile time.
When does a constexpr function get
Just to not leave it buried in comments:
#include <type_traits>
#define COMPILATION_EVAL(e) (std::integral_constant<decltype(e), e>::value)
constexpr int f(int i){return i;}
int main()
{
int x = COMPILATION_EVAL(f(0));
}
One caveat with this approach, constexpr
functions can accept floating-point and be assigned to constexpr
floating-point variables, but you cannot use a floating-point type as a non-type template parameter. Also, same limitations for other kinds of literals.
Your lambda would work for that, but I guess you would need a default-capture to get meaningful error message when non-constexpr
stuff get passed to the function. That ending std::move
is dispensable.
Err, your lambda approach doesn't work for me, I just realized, how it can even work, the lambda is not a constexpr
function. It should not be working for you too.
It seems there's really no way around it but initializing a constexpr
variable in local scope.
Oh, ok, my bad, the purpose of the lambda is just the evaluation. So it's working for that. Its result, instead, is which is unusable to follow another compilation time eval.
On C++17, lambdas now can be used in constexpr contexts, so the limitation referred to in EDIT2/EDIT3 is removed! So the lambda solution is the correct one. See this comment for more information.