Assuming i have some function template f1:
template<typename f2>
int f1(int i, int j) noexcept {
return i + j + f2(i, j);
}
is there way to determine if f2(i, j)
can be a constexpr
. (no matter it is a func. or a functor) and so mark f1<f2>
as a constexpr
too?
I am thinking of using SFINAE here some how, but didn't find how to detect constexpr
using type traits
The easiest way to check whether a function (e.g., foo ) is constexpr is to assign its return value to a constexpr as below: constexpr auto i = foo(); if the returned value is not constexpr compilation will fail.
A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.
A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.
Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.
You can mark f1
as constexpr
.
template<typename f2>
constexpr int f1(int i, int j) noexcept {
return i + j + f2(i, j);
}
The template function f1
would be constexpr
iif f2
is.
if f2
is not, you will get error only when you use f1
in a constant compile time expression.
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With