“The easiest way to solve a problem is to deny it exists.”
― Isaac Asimov
P0597R0 proposed to add a new std::constexpr_vector type that is usable in constexpr context. That's going to be a very useful class and many people already wish to have it in Standard Library.
However, users will definitely wish for more:
pop_front functionconstexprThis proposal is not an attempt to prevent further work on P0597R0. This proposal is an attempt to change problem attack vector of the P0597R0 to make it more generic and solve more problems without duplicating each container in the Standard Library.
Instead of providing multiple constexpr containers we can provide a single std::constexpr_allocator and mark existing containers with constexpr.
It took roughly 10 man-hours to implement naive std::constexpr_allocator as a library only solution and tune std::vector to be usable in constexpr context. Now it is possible to write code like the following:
constexpr bool vector_testing_constexpr(unsigned size) {
std::vector<unsigned, constexpr_allocator<unsigned>> compile_time;
for (unsigned i = 0; i <= size; ++ i)
compile_time.push_back(i);
compile_time.emplace_back(0);
compile_time.pop_back();
return compile_time.back() == size;
}
int main() {
constexpr auto r = vector_testing_constexpr(5);
static_assert(r, "");
}
The proof of concept implementation could be found at https://github.com/ZaMaZaN4iK/constexpr_allocator (all the major changes are in modif_* headers).
Following problems were discovered while implementing the proof of concept prototype:
constexpr
constexpr all around the container declarationconstexpr specifiers
try and catch are not allowed in constant expressions
try and catch in constant expressions that just do nothingconstexpr_vector that allocates memory, please change it to magic constexpr_allocator that allocates memory in constant expressions.placement new in constant expressions, so no way to implement constexpr_allocator::construct
constructor+move_assignment. That's the solution that was used in the prototypeplacement new in constexpr expressions.Pros of constexpr_allocator approach:
new, we won't need to deprecate a bunch of constexpr containers. We'll just deprecate a single constexpr allocatorstd::constexpr_vector.Cons of constexpr_allocator approach:
std::constexpr_vector proposal the constexpr_allocator approach requires multiple smaller proposals to cycle trough almost all the subgroups.[P0597R0] "std::constexpr_vector<T>" proposal. Available online at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0597r0.html
[P0202R1] "Add Constexpr Modifiers to Functions in <algorithm> and <utility> Headers" proposal. Available online at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0202r1.html
Daveed Vandevoorde highlighted some challenges during early review of the paper.