Document number: P0639R0
Project: Programming Language C++
Audience: Evolution Working Group, Library Evolution Working Group
 
Antony Polukhin <antoshkka@gmail.com>, <antoshkka@yandex-team.ru>
Alexander Zaitsev <zamazan4ik@tut.by>
 
Date: 2017-06-14

Changing attack vector of the constexpr_vector

“The easiest way to solve a problem is to deny it exists.”

― Isaac Asimov

I. Introduction and Motivation

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:

This 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.

II. The idea

Instead of providing multiple constexpr containers we can provide a single std::constexpr_allocator and mark existing containers with constexpr.

III. Proof of concept

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).

IV. Challenges and solutions

Following problems were discovered while implementing the proof of concept prototype:

V. Pros and Cons

Pros of constexpr_allocator approach:

Cons of constexpr_allocator approach:

VI. References

[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

 

 

VII. Acknowledgements

Daveed Vandevoorde highlighted some challenges during early review of the paper.