For most algorithms and utility classes (std::bitset
, std::array
, etc.) in the standard library, you can simply add the constexpr
specifier everywhere and try and store the result in a constexpr
variable. Most likely, this will compile and run successfully. See also this Q&A.
What will typically stop such code from compiling is one of the current language restrictions on compile-time constant expressions, such as (look at 5.20 Constant expressions [expr.const] for the full list)
- dynamic memory allocation (inside
std::inplace_merge
e.g.)
- virtual functions (in
<iostream>
)
- lambda expressions (proposed and accepted for standardization in N4487)
reinterpret_cast
goto
(proposed but rejected for standardization in N4472)
For each restriction, there are ways to get around it
- The alternative to the system supported dynamic memory allocation
through
new
/delete
is to write your own memory pool in a large
global constexpr
array.
- The alternative to virtual functions is to store an array of function
pointers (that call
constexpr
functions) and dispatch them through
a switch
statement.
- The alternative to lambdas is to write your own function objects with
a
constexpr operator()
.
- The alternative to
reinterpret_cast
is to use a constexpr
variant (with a union
underneath it).
- The alternative to
goto
is to write more structured code using
regular loops and branches.
In all cases, you will lose the syntactic niceties of being able to call new
/delete
or implicit dynamic dispatching. You will have to manually allocate/deallocate your memory and to manually select your function pointer.
Note that even though large parts of the standard library could be made constexpr
even with the current C++14/17 language, they currently are not. Moreover, standard library implementors are forbidden from adding extra constexpr
functionality (in contrast from being allowed to offer stronger noexcept
support).
Complain to your vendors or the C++ committee if you think there should be more or easier constexpr
support (both in the language and the standard library).