Is it possible to produce a compile-time boolean value based on whether or not a C++11 expression is a constant expression (i.e. constexpr
) in C++11? A few questions on SO relate to this, but I don't see a straight answer anywhere.
C++11 – Is is_constexpr Possible?
c++c++11compile-timeconstexpr
Best Answer
I once wrote it (EDIT: see below for limitations and explanations). From https://stackoverflow.com/a/10287598/34509 :
However there are many kinds of constant expressions. The above answer detects prvalue constant expressions.
Explanation
The
noexcept(e)
expression givesfalse
iffe
containsthrow
expression,dynamic_cast
ortypeid
.Note that the function template
makeprval
is not declarednoexcept
, so the call needs to be a constant expression for the first bullet not to apply, and this is what we abuse. We need the other bullets to not apply aswell, but thanksfully, both athrow
and a throwabledynamic_cast
ortypeid
aren't allowed in constant expressions aswell, so this is fine.Limitations
Unfortunately there is a subtle limitation, which may or may not matter for you. The notion of "potentially evaluated" is much more conservative than the limits of what constant expressions apply. So the above
noexcept
may give false negatives. It will report that some expressions aren't prvalue constant expressions, even though they are. Example:In the above
atest
is false, even though the initialization ofa
succeeded. That is because for being a constant expression, it suffices that the "evil" non-constant sub-expressions are "never evaluated", even though those evil sub-expressions are potentially-evaluated, formally.