Since the extended versions of constexpr
(I think from C++14) you can declare constexpr
functions that could be used as "real" constexpr
. That is, the code is executed at compile time or can behave as inline functions. So when can have this program:
#include <iostream>
constexpr int foo(const int s) {
return s + 4;
}
int main()
{
std::cout << foo(3) << std::endl;
const int bar = 3;
std::cout << foo(bar) << std::endl;
constexpr int a = 3;
std::cout << foo(a) << std::endl;
return 0;
}
The result is:
7
7
7
So far so good.
Is there a way (possibly standard) to know inside foo(const int s)
if the function is executed at compile time or at runtime?
EDIT: Also is it possible to know at runtime if a function was evaluated at compile time?
template <int x> struct bar {}; bar<foo(3)>;
– Thinkconstexpr
context. :-/ Jason Turner has talked about this topic at length in a video where he talks about making a JSON parser that runs at compile time. – Hornwortstatic const
variable and then use that variable instead of the expression. No need to go to all the effort of having it be a template parameter. – Hornwortconst int x
in that context is a constexpr, so no. – Notedstatic_assert
. Or assign its results to aconstexpr
object. – Zorinaconstexpr
functions were designed to fulfill an intent under certain constraints; And there are ways to ensure it does, for example - by assigning it to aconstexpr
variable; if we can't get the results at compile time, we have an error.. Why do you want to know whether it did or not without a compile error. How is it going to be useful to your program? – Zorinaconsteval
if you need guaranteed compile time evaluation. – Bujumbura