Is it possible to test whether something is constexpr? [duplicate] - c++

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.

I once wrote it (EDIT: see below for limitations and explanations). From https://stackoverflow.com/a/10287598/34509 :
template<typename T>
constexpr typename remove_reference<T>::type makeprval(T && t) {
return t;
}
#define isprvalconstexpr(e) noexcept(makeprval(e))
However there are many kinds of constant expressions. The above answer detects prvalue constant expressions.
Explanation
The noexcept(e) expression gives false iff e contains
a potentially evaluated call to a function that does not have a non-throwing exception-specification unless the call is a constant expression,
a potentially evaluated throw expression,
a potentially evaluated throwable form of dynamic_cast or typeid.
Note that the function template makeprval is not declared noexcept, 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 a throw and a throwable dynamic_cast or typeid 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:
constexpr int a = (0 ? throw "fooled!" : 42);
constexpr bool atest = isprvalconstexpr((0 ? throw "fooled!" : 42));
In the above atest is false, even though the initialization of a 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.

As of 2017, is_constexpr is not possible in C++11. That sounds like an odd thing to say, so let me explain a bit of the history.
First, we added this feature to resolve a defect: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1129
Johannes Schaub - litb posted a constexpr detection macro that relied on the provision that constant expressions are implicitly noexcept. This worked in C++11, but was never implemented by at least some compilers (for instance, clang). Then, as part of C++17, we evaluated Removing Deprecated Exception Specifications from C++17. As a side-effect of that wording, we accidentally removed that provision. When the Core Working Group discussed adding the provision back in, they realized that there were some serious problems with doing so. You can see the full details in the LLVM bug report. So rather than adding it back in, we decided to consider it a defect against all versions of standard and retroactively removed it.
The effect of this is that there is, to my knowledge, no way to detect whether an expression is usable as a constant expression.

Yes, this is possible. One way to do it (which is valid even with the recent noexcept changes) is to take advantage of the C++11 narrowing conversion rules:
A narrowing conversion is an implicit conversion [...] from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
(emphasis mine). List initialization generally disallows narrowing conversions, and when combined with SFINAE we can build gadgets for detecting whether an arbitrary expression is a constant expression:
// p() here could be anything
template<int (*p)()> std::true_type is_constexpr_impl(decltype(int{(p(), 0U)}));
template<int (*p)()> std::false_type is_constexpr_impl(...);
template<int (*p)()> using is_constexpr = decltype(is_constexpr_impl<p>(0));
constexpr int f() { return 0; }
int g() { return 0; }
static_assert(is_constexpr<f>());
static_assert(!is_constexpr<g>());
Live demonstration.
The key here is that int{(expr, 0U)} contains a narrowing conversion from unsigned int to int (and thus is ill-formed), unless expr is a constant expression, in which case the entire expression (expr, 0U) is a constant expression whose evaluated value fits into the type int.

The following is an implementation of is_constexpr for functions, not for arbitrary expressions, for C++11 and C++17. It requires the arguments to the function you want to test to be default constructible, though.
#include <type_traits>
struct A {}; // don't make it too easy, use a UDT
A f1(A a) { return a; } // is_constexpr -> false
constexpr A f2(A a) { return a; } // is_constexpr -> true
// The following turns anything (in our case a value of A) into an int.
// This is necessary because non-type template arguments must be integral
// (likely to change with C++20).
template <class T> constexpr int make_int(T &&) { return 0; }
// Helper to turn some function type (e.g. int(float)) into a function
// pointer type (e.g. int (*)(float)).
template <class T> struct signature_from;
template <class R, class... Args> struct signature_from<R(Args...)> {
using type = R(*)(Args...);
};
// See std::void_t for the idea. This does it for ints instead of types.
template <int...> using void_from_int = void;
// The fallback case: F is not a function pointer to a constexpr function
template <class T, typename signature_from<T>::type F, class = void_from_int<>>
struct is_constexpr {
static constexpr bool value = false;
};
// If void_from_int<make_int(F(Args()...))> doesn't lead to a substitution
// failure, then this is the preferred specialization. In that case F must
// be a function pointer to a constexpr function. If it is not, it could
// not be used in a template argument.
template <class R, class... Args, typename signature_from<R(Args...)>::type F>
struct is_constexpr<R(Args...), F, void_from_int<make_int(F(Args()...))>>
{
static constexpr bool value = true;
};
// proof that it works:
static_assert(!is_constexpr<A(A), f1>::value, "");
static_assert( is_constexpr<A(A), f2>::value, "");
#if __cplusplus >= 201703
// with C++17 the type of the function can be deduced:
template<auto F> struct is_constexpr2 : is_constexpr<std::remove_pointer_t<decltype(F)>, F> {};
static_assert(!is_constexpr2<f1>::value, "");
static_assert( is_constexpr2<f2>::value, "");
#endif
See it in action at https://godbolt.org/g/rdeQme.

C++20 added std::is_constant_evaluated()
This allows checking if a certain expression is a constant evaluated expression, i.e. being evaluated at compile time.
Usage example:
constexpr int foo(int num) {
// below is true in case the condition is being evaluated at compile time
// side note, using: if constexpr (std::is_constant_evaluated())
// would be evaluated always to true, so you should use a simple if!
if (std::is_constant_evaluated()) {
return foo_compiletime(num);
}
else {
return foo_runtime(num);
}
}
int main() {
constexpr auto t1 = foo(6); // reaches foo_compiletime
const auto t2 = foo(6); // reaches foo_compiletime
int n = rand() % 10;
const auto t3 = foo(n); // reaches foo_runtime
auto t4 = foo(6); // unfortunately, reaches foo_runtime
}
The last call in the example above would reach foo_runtime, since the call is not within a constant expression context (the result is not being used as a constant expression, see also this SO answer).
This may lead to undesired pessimization, compared to the case of leaving the decision to the user, who may call:
auto t4 = foo_compiletime(6);
And the compiler is allowed to perform the operations inside foo_compiletime at compile time, if it is declared as constexpr function, or would be obliged to do that if it is declared consteval. However, once we leave the decision to the compiler, we will reach foo_runtime, unless we explicitly direct the compiler to go for foo_compiletime, by taking the result into a const, constexpr or constinit variable. Which then, in a way, omits the value of having one function for both scenarios, if the user is required to help the compiler peek the right path.
Another possible option for the call to be optimized, is:
constexpr auto temp = foo(6); // foo_compiletime
auto t4 = temp;
But again, we require the user to be aware of the inner behavior of foo, which is not exactly what we want to achieve.
See the pessimization in this code.
See more on that in this great blog post on the subject.

Related

Statically asserting the size of a std::array whose type is obtained using decltype from the return value of a member function

I want to write a free function that can automatically determine the type of its parameter, based on the return value of a member function of a class. Using decltype, that part is easy.
I also want to have a compile-time assertion to verify an assumption being made about that parameter type, and this is where my proposed solution falls apart.
Consider the following MCVE:
#include <type_traits>
#include <array>
#include <iostream>
class Foo
{
public:
std::array<int, 10> Get();
};
void PrintFoos(const decltype(Foo().Get())& param)
{
static_assert(param.size() == 10, "wrong size");
for (const auto& i : param)
{
std::cout << i << "\n";
}
}
GCC compiles the above code just fine, with nary a warning.
Clang, on the other hand, gripes:
error: static_assert expression is not an integral constant expression
static_assert(param.size() == 10, "wrong size");
^~~~~~~~~~~~~~~~~~
So does MSVC:
(13): error C2131: expression did not evaluate to a constant
(13): note: failure was caused by a read of a variable outside its lifetime
(13): note: see usage of 'param'
Why does GCC compile this fine, when other compilers reject it? Is there a GCC extension that I'm benefitting from to support this?
What does the language standard have to say about this? I am targeting C++17, but would also be interested in knowing if there are any changes from C++14.
Bonus Question: Is there a way that I can modify this code to make it work? Obviously, the static_assert should fail if the decltype expression does not evaluate to a std::array type, since the size() member function would not be constexpr. I imagine there is a solution involving the addition of a template helper function, but I'd rather not add another function definition unless absolutely necessary.
I believe clang and the others (icc and MSVC) are technically correct here and GCC is wrong. A static_assert-declaration takes a constant-expression [expr.const]/2. I believe the relevant C++17 wording for the case at hand should be [expr.const]/2.11:
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:
[…]
an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
it is initialized with a constant expression or
its lifetime began within the evaluation of e;
[…]
The expression in your static_assert above clearly does exactly that, however (param is an id-expression that refers to a variable of reference type, none of the exceptions apply). Thus, it is not a constant expression, and the program is ill-formed [dcl.dcl]/6. The relevant wording in the C++14 standard seems to be identical. I woud consider this a bug in GCC.
If you can change your function into a template, you could simply infer the size:
template <int N>
void PrintFoos(const std::array<int, N>& param)
{
…
}
Alternatively, if you want to make everything depend on Foo, you could also just define a public constant and derive the array type etc. from that:
class Foo
{
public:
static constexpr auto size = 10;
std::array<int, size> Get();
};
void PrintFoos(const decltype(Foo().Get())& param)
{
static_assert(Foo::size == 10, "wrong size");
}
And, of course, you could use a helper template:
template <typename T>
constexpr std::size_t deduce_array_size = 0U;
template <typename T, std::size_t N>
constexpr std::size_t deduce_array_size<std::array<T, N>> = N;
template <typename T>
constexpr std::size_t deduce_array_size<T&> = deduce_array_size<T>;
template <typename T>
constexpr std::size_t deduce_array_size<T&&> = deduce_array_size<T>;
and then
void PrintFoos(const decltype(Foo().Get())& param)
{
static_assert(deduce_array_size<decltype(param)> == 10, "wrong size");
}
Finally, yet another option (inspired by the comment by Yakk - Adam Nevraumont below) would be to simply create a prvalue of the array type in your constant expression and ask that for its size:
static_assert(std::decay_t<decltype(param)>{}.size() == 10, "wrong size");

convert strongly typed enumerator to its underlying type in compilation time?

I understand that a strongly typed enumerator can be converted to its underlying type as:
template<typename E> constexpr
auto to_integral(E e) -> typename std::underlying_type<E>::type
{
return static_cast<typename std::underlying_type<E>::type>(e);
}
However, this is working in run-time.
Since enumerators are there already in compilation time, is there a way to do such conversion during compilation time?
As herb sutter mentioned in the below link,
When does a constexpr function get evaluated at compile time?
constexpr functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well. A constant expression could be a literal (like 42), a non-type template argument (like N in template class array;), an enum element declaration (like Blue in enum Color { Red, Blue, Green };, another variable declared constexpr, and so on.
They might be evaluated when all its arguments are constant expressions and the result is not used in a constant expression, but that is up to the implementation.
The function you wrote is OK to be used at compile time.
template<typename E> constexpr
auto to_integral(E e) -> typename std::underlying_type<E>::type
{
return static_cast<typename> std::underlying_type<E>::type>(e);
}
enum class A : int { a };
static_assert(to_integral(A::a) == 0);
This should compile, indicating that the function can be ran at compile time.
However, constexpr functions only indicate that the function complies with all requirements to be executed at compile time. To enforce this being calculated (even at -O0), you need to make your variables also constexpr.
constexpr auto i = to_integral(A::a);
i = 42;
For a variable, the constexpr simply means: initialize at compile time. Afterwards, you can use it as if it was runtime.
In the example above, I'm convinced that most compilers will optimize the code regardless of the constexpr keyword. (Given -O2 or -O3) However if the code becomes more complex the constexpr is required to force them to optimize it, regardless of the cost.

Implementing is_constexpr_copiable

I tried to implement a value template similar to std::is_constructible with the exception to only be true when the type is copiable in a constexpr environment (i.e. its copy constructor is constexpr qualified). I arrived at the following code:
#include <type_traits>
struct Foo {
constexpr Foo() = default;
constexpr Foo(const Foo&) = default;
};
struct Bar {
constexpr Bar() = default;
Bar(const Bar&);
};
namespace detail {
template <int> using Sink = std::true_type;
template<typename T> constexpr auto constexpr_copiable(int) -> Sink<(T(T()),0)>;
template<typename T> constexpr auto constexpr_copiable(...) -> std::false_type;
}
template<typename T> struct is_constexpr_copiable : decltype(detail::constexpr_copiable<T>(0)){ };
static_assert( is_constexpr_copiable<Foo>::value, "");
static_assert(!is_constexpr_copiable<Bar>::value, "");
Now I ask myself if this is according to standard, since compilers seem to disagree about the output.
https://godbolt.org/g/Aaqoah
Edit (c++17 features):
While implementing the somewhat different is_constexpr_constructible_from, with c++17's new auto non-type template type, I once again found a difference between compilers, when dereferencing a nullptr in a constexpr expression with SFINAE.
#include <type_traits>
struct Foo {
constexpr Foo() = default;
constexpr Foo(const Foo&) = default;
constexpr Foo(const Foo*f):Foo(*f) {};
};
struct Bar {
constexpr Bar() = default;
Bar(const Bar&);
};
namespace detail {
template <int> struct Sink { using type = std::true_type; };
template<typename T, auto... t> constexpr auto constexpr_constructible_from(int) -> typename Sink<(T(t...),0)>::type;
template<typename T, auto... t> constexpr auto constexpr_constructible_from(...) -> std::false_type;
}
template<typename T, auto... t> struct is_constexpr_constructible_from : decltype(detail::constexpr_constructible_from<T, t...>(0)){ };
constexpr Foo foo;
constexpr Bar bar;
static_assert( is_constexpr_constructible_from<Foo, &foo>::value, "");
static_assert(!is_constexpr_constructible_from<Foo, nullptr>::value, "");
static_assert(!is_constexpr_constructible_from<Bar, &bar>::value, "");
int main() {}
https://godbolt.org/g/830SCU
Edit: (April 2018)
Now that both compiler supposedly have support for C++17, I have found the following code to work even better (does not require a default constructor on `T`), but only on clang. Everything is still the same but replace the namespace `detail` with the following:
namespace detail {
template struct Sink {};
template constexpr auto sink(S) -> std::true_type;
template constexpr auto try_copy() -> Sink;
template constexpr auto constexpr_copiable(int) -> decltype(sink(std::declval,0)>>()));
template constexpr auto constexpr_copiable(...) -> std::false_type;
}
https://godbolt.org/g/3fB8jt
This goes very deep into parts of the standard about unevaluated context, and both compilers refuse to allow replacing `const T*` with `const T&` and using `std::declval()` instead of the `nullptr`-cast. Should I get confirmation that clang's behaviour is the accepted standardized behaviour, I will lift this version to an answer as it requires only exactly what has been asked.
Clang accepts some undefined behaviour, dereferencing nullptr, in the evaluation of an unevaluated operand of decltype.
The toughest of the challenges, giving a single function evaluating whether a constexpr constructor from const T& exists for arbitrary T, given here seems hardly possible in C++17. Luckily, we can get a long way without. The reasoning for this goes as follows:
Knowing the problem space
The following restrictions are important for determining if some expression can be evaluated in constexpr content:
To evaluate the copy constructor of T, a value of type const T& is needed. Such a value must refer to an object with active lifetime, i.e. in constexpr context it must refer to some value created in a logically enclosing expression.
In order to create this reference as a result of temporary promotion for arbitrary T as we would need to know and call a constructor, whose arguments could involve virtually arbitrary other expressions whose constexpr-ness we would need to evaluate. This looks like it requires solving the general problem of determining the constexprness of general expressions, as far as I can understand. ¹
¹ Actually, If any constructor with arguments, including the copy constructor, is defined as constexpr, there must be some valid way of constructing a T, either as aggregate initialization or through a constructor. Otherwise, the program would be ill-formed, as can be determined by the requirements of the constexpr specifier §10.1.5.5:
For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required.
This might give us a tiny loophole.²
So the expression best be an unevaluated operand §8.2.3.1
In some contexts, unevaluated operands appear ([expr.prim.req], [expr.typeid], [expr.sizeof], [expr.unary.noexcept], [dcl.type.simple], [temp]).
An unevaluated operand is not evaluated
Unevaluated operands are general expressions but they can not be required to be evaluatable at compile time as they are not evaluated at all. Note that the parameters of a template are not part of the unevaluated expressiont itself but rather part of the unqualified id naming the template type. That was part of my original confusion and tries in finding a possible implementation.
Non-type template arguments are required to be constant expressions §8.6 but this property is defined through evaluation (which we have already determined to not be generally possible). §8.6.2
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would [highlight by myself] evaluate one of the following expressions:
Using noexpect for the unevaluated context has the same problem: The best discriminator, inferred noexceptness, works only on function calls which can be evaluated as a core-constant expression, so the trick mentionend in this stackoverflow answer does not work.
sizeof has the same problems as decltype. Things may change with concepts.
The newly introduced if constexpr is, sadly, not an expression but a statement with an expression argument. It can therefore not help enforce the constexpr evaluatability of an expression. When the statement is evaluated, so is its expression and we are back at the problem of creating an evaluatable const T&. Discarded statements have not influence on the process at all.
Easy possibilities first
Since the hard part is creating const T&, we simply do it for a small number of common but easily determined possibilities and leave the rest to specialization by extremely special case callers.
namespace detail {
template <int> using Sink = std::true_type;
template<typename T,bool SFINAE=true> struct ConstexprDefault;
template<typename T>
struct ConstexprDefault<T, Sink<(T{}, 0)>::value> { inline static constexpr T instance = {}; };
template<typename T> constexpr auto constexpr_copiable(int) -> Sink<(T{ConstexprDefault<T>::instance}, 0)>;
template<typename T> constexpr auto constexpr_copiable(...) -> std::false_type;
}
template<typename T>
using is_constexpr_copyable_t = decltype(detail::constexpr_copiable<T>(0));
Specializing details::ConstexprDefault must be possible for any class type declaring a constexpr copy constructor, as seen above. Note that the argument does not hold for other compound types which don't have constructors §6.7.2. Arrays, unions, references and enumerations need special considerations.
A 'test suite' with a multitude of types can be found on godbolt. A big thank you goes to reddit user /u/dodheim from whom I have copied it. Additional specializations for the missing compound types are left as an exercise to the reader.
² or What does this leave us with?
Evaluation failure in template arguments is not fatal. SFINAE makes it possible to cover a wide range of possible constructors. The rest of this section is purely theoretical, not nice to compilers and might otherwise be plainly stupid.
It is potentially possible to enumerate many constructors of a type using methods similar to magic_get. Essentially, use a type Ubiq pretending to be convertible to all other types to fake your way through decltype(T{ ubiq<I>()... }) where I is a parameter pack with the currently inspected initializer item count and template<size_t i> Ubiq ubiq() just builds the correct amount of instances. Of course in this case the cast to T would need to be explicitely disallowed.
Why only many? As before, some constexpr constructor will exist but it might have access restrictions. This would give a false positive in our templating machine and lead to infinite search, and at some time the compiler would die :/. Or the constructor might be hidden by an overload which can not be resolved as Ubiq is too general. Same effect, sad compiler and a furious PETC (People for the ethical treatment of compilers™, not a real organization). Actually, access restrictions might be solvable by the fact that those do not apply in template arguments which may allow us to extract a pointer-to-member and [...].
I'll stop here. As far as I can tell, it's tedious and mostly unecessary. Surely, covering possible constructor invocations up 5 arguments will be enough for most use cases. Arbitrary T is very, very hard and we may as well wait for C++20 as template metaprogramming is once again about to change massively.

C++ constexpr auto member function. Clang issue?

#include <utility>
struct A {
constexpr auto one(int a) {
return std::integral_constant<int, _data[a]>{};
}
constexpr int two(int a) const {
return _data[a];
}
int _data[10];
};
int main() {
constexpr auto ex = A{{1,2,3,4,5,6,7,8,9,10}};
std::integral_constant<int, ex.two(3)> b{};
}
The code above will not compile in trunk Clang. The error is in the one() member function, and says:
cc.cpp:57:44: note: implicit use of 'this' pointer is only allowed
within the evaluation of a call to a 'constexpr' member function.
Obviously, the function is marked constexpr, and if you comment out the one() member, everything compiles fine, so we are clearly able to create the integral_constant from the ex, but not directly from the struct? It seems like, when I need the auto return type deduction, it fails and claims the function is not constexpr?
Is this expected? I feel like it should not be a problem, and I would be surprised if this was expected behavior.
If you consider this statement in [dcl.constexpr]/7:
A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that a call to a constexpr function can appear in a constant expression.
Consider the non-constexpr equivalent function A::one(). _data[a] cannot be used in a constant expression (as a non-type template argument) because it would involve the evaluation of this, from [expr.const]:
A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the
abstract machine (1.9), would evaluate one of the following expressions:
(2.1) — this (5.1.1), except in a constexpr function or a constexpr constructor that is being evaluated as
part of e;
Since the non-constexpr equivalent is ill-formed, it is reasonable that the constexpr function give the same result.
Ont the other hand, two() is a well-formed member function regardless of constexpr and your use of ex.two(3) is valid as a constant expression - that's why it compiles.
constexpr functions are made so that they can be called both at compile-time and run-time.
Code with a constexpr function is well-formed if you can omit constexpr and get a proper plain function. In other words it must compile as a run-time function.
If the body of constexpr function cannot be calculated at compile-time, it's still compiled, but you cannot use it in a compile-time context such as template arguments.
If constexpr method is called on constexpr object, this is considered constexpr.
In case of one it is ill-formed, because when it's compiled to be run at run-time, _data[a] is considered to be a run-time expression, because a is not a constant expression, even though this and this->_data are.
In case of two it compiles fine, because it works fine at runtime, and at compile-time this is constexpr as much as a, so that this->_data[a] is constexpr and everything works fine.

Is is_constexpr possible in C++11?

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.
I once wrote it (EDIT: see below for limitations and explanations). From https://stackoverflow.com/a/10287598/34509 :
template<typename T>
constexpr typename remove_reference<T>::type makeprval(T && t) {
return t;
}
#define isprvalconstexpr(e) noexcept(makeprval(e))
However there are many kinds of constant expressions. The above answer detects prvalue constant expressions.
Explanation
The noexcept(e) expression gives false iff e contains
a potentially evaluated call to a function that does not have a non-throwing exception-specification unless the call is a constant expression,
a potentially evaluated throw expression,
a potentially evaluated throwable form of dynamic_cast or typeid.
Note that the function template makeprval is not declared noexcept, 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 a throw and a throwable dynamic_cast or typeid 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:
constexpr int a = (0 ? throw "fooled!" : 42);
constexpr bool atest = isprvalconstexpr((0 ? throw "fooled!" : 42));
In the above atest is false, even though the initialization of a 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.
As of 2017, is_constexpr is not possible in C++11. That sounds like an odd thing to say, so let me explain a bit of the history.
First, we added this feature to resolve a defect: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1129
Johannes Schaub - litb posted a constexpr detection macro that relied on the provision that constant expressions are implicitly noexcept. This worked in C++11, but was never implemented by at least some compilers (for instance, clang). Then, as part of C++17, we evaluated Removing Deprecated Exception Specifications from C++17. As a side-effect of that wording, we accidentally removed that provision. When the Core Working Group discussed adding the provision back in, they realized that there were some serious problems with doing so. You can see the full details in the LLVM bug report. So rather than adding it back in, we decided to consider it a defect against all versions of standard and retroactively removed it.
The effect of this is that there is, to my knowledge, no way to detect whether an expression is usable as a constant expression.
Yes, this is possible. One way to do it (which is valid even with the recent noexcept changes) is to take advantage of the C++11 narrowing conversion rules:
A narrowing conversion is an implicit conversion [...] from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
(emphasis mine). List initialization generally disallows narrowing conversions, and when combined with SFINAE we can build gadgets for detecting whether an arbitrary expression is a constant expression:
// p() here could be anything
template<int (*p)()> std::true_type is_constexpr_impl(decltype(int{(p(), 0U)}));
template<int (*p)()> std::false_type is_constexpr_impl(...);
template<int (*p)()> using is_constexpr = decltype(is_constexpr_impl<p>(0));
constexpr int f() { return 0; }
int g() { return 0; }
static_assert(is_constexpr<f>());
static_assert(!is_constexpr<g>());
Live demonstration.
The key here is that int{(expr, 0U)} contains a narrowing conversion from unsigned int to int (and thus is ill-formed), unless expr is a constant expression, in which case the entire expression (expr, 0U) is a constant expression whose evaluated value fits into the type int.
The following is an implementation of is_constexpr for functions, not for arbitrary expressions, for C++11 and C++17. It requires the arguments to the function you want to test to be default constructible, though.
#include <type_traits>
struct A {}; // don't make it too easy, use a UDT
A f1(A a) { return a; } // is_constexpr -> false
constexpr A f2(A a) { return a; } // is_constexpr -> true
// The following turns anything (in our case a value of A) into an int.
// This is necessary because non-type template arguments must be integral
// (likely to change with C++20).
template <class T> constexpr int make_int(T &&) { return 0; }
// Helper to turn some function type (e.g. int(float)) into a function
// pointer type (e.g. int (*)(float)).
template <class T> struct signature_from;
template <class R, class... Args> struct signature_from<R(Args...)> {
using type = R(*)(Args...);
};
// See std::void_t for the idea. This does it for ints instead of types.
template <int...> using void_from_int = void;
// The fallback case: F is not a function pointer to a constexpr function
template <class T, typename signature_from<T>::type F, class = void_from_int<>>
struct is_constexpr {
static constexpr bool value = false;
};
// If void_from_int<make_int(F(Args()...))> doesn't lead to a substitution
// failure, then this is the preferred specialization. In that case F must
// be a function pointer to a constexpr function. If it is not, it could
// not be used in a template argument.
template <class R, class... Args, typename signature_from<R(Args...)>::type F>
struct is_constexpr<R(Args...), F, void_from_int<make_int(F(Args()...))>>
{
static constexpr bool value = true;
};
// proof that it works:
static_assert(!is_constexpr<A(A), f1>::value, "");
static_assert( is_constexpr<A(A), f2>::value, "");
#if __cplusplus >= 201703
// with C++17 the type of the function can be deduced:
template<auto F> struct is_constexpr2 : is_constexpr<std::remove_pointer_t<decltype(F)>, F> {};
static_assert(!is_constexpr2<f1>::value, "");
static_assert( is_constexpr2<f2>::value, "");
#endif
See it in action at https://godbolt.org/g/rdeQme.
C++20 added std::is_constant_evaluated()
This allows checking if a certain expression is a constant evaluated expression, i.e. being evaluated at compile time.
Usage example:
constexpr int foo(int num) {
// below is true in case the condition is being evaluated at compile time
// side note, using: if constexpr (std::is_constant_evaluated())
// would be evaluated always to true, so you should use a simple if!
if (std::is_constant_evaluated()) {
return foo_compiletime(num);
}
else {
return foo_runtime(num);
}
}
int main() {
constexpr auto t1 = foo(6); // reaches foo_compiletime
const auto t2 = foo(6); // reaches foo_compiletime
int n = rand() % 10;
const auto t3 = foo(n); // reaches foo_runtime
auto t4 = foo(6); // unfortunately, reaches foo_runtime
}
The last call in the example above would reach foo_runtime, since the call is not within a constant expression context (the result is not being used as a constant expression, see also this SO answer).
This may lead to undesired pessimization, compared to the case of leaving the decision to the user, who may call:
auto t4 = foo_compiletime(6);
And the compiler is allowed to perform the operations inside foo_compiletime at compile time, if it is declared as constexpr function, or would be obliged to do that if it is declared consteval. However, once we leave the decision to the compiler, we will reach foo_runtime, unless we explicitly direct the compiler to go for foo_compiletime, by taking the result into a const, constexpr or constinit variable. Which then, in a way, omits the value of having one function for both scenarios, if the user is required to help the compiler peek the right path.
Another possible option for the call to be optimized, is:
constexpr auto temp = foo(6); // foo_compiletime
auto t4 = temp;
But again, we require the user to be aware of the inner behavior of foo, which is not exactly what we want to achieve.
See the pessimization in this code.
See more on that in this great blog post on the subject.