Unfortunately, there is no way guarantee that a constexpr function, even the most trivial one, will be evaluated by the compiler unless absolutely necessary. That is, unless it appears in a place where its value is required at compile time, e.g. in a template. In order to enforce the compiler to do the evaluation during compilation, you can do the following:
constexpr int foo_implementation (int x) { return x + 1; } #define foo(x) std::integral_constant<int, foo_implementation(x)>::value
and then use foo in your code as usual
int f = foo(123);
The nice thing about this approach is that it guarantees compile-time evaluation, and you'll get a compilation error if you pass a run-time variable to foo:
int a = 2; int f = foo(a); /* Error: invalid template argument for 'std::integral_constant', expected compile-time constant expression */
The not so nice thing is that it requires a macro, but this seems currently inevitable if you want both guaranteed compile-time evaluation and pretty code. (I'd love to be proven wrong though!)
template<int x> int foo() { return x + 1; }constexprwas partially called into being to counteract all the syntactical workarounds you are going to see in the answers here.#define foo(N) foo<N>()looks viable to me.#define REQUIRE_CEXPR(E) []{ constexpr auto x = E; return x; }()and you can sayfoo(REQUIRE_CEXPR(1 + 2))(C++14). For C++11, you can do[]()->typename std::decay<decltype((E))>::typeto explicitly specify the type. Uglier though :)constexpr.