In C++20, many (most?) C++-standard-library algorithms have been made constexpr
. Yet - std::accumulate
has not.
It seems like it could have been:
template<class InputIt, class T>
constexpr T accumulate(InputIt first, InputIt last, T init)
{
for (; first != last; ++first) {
init = std::move(init) + *first;
}
return init;
}
So - is there a reason it wasn't constexpr
'ed as well?
Note: This question was motivated by my answer to this question on compile-time accumulation.
constexpr function can call only other constexpr function not simple function. The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function. It removes the function calls as it evaluates the code/expressions in compile time.
C++20 supports the constexpr containers std::vector and std::string. constexpr means in this case, that the member functions of both containers can be applied at compile-time. Before I write about both containers, I have to make a short detour to C++17.
In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement. constexpr function should refer only to constant global variables. constexpr function can call only other constexpr function not simple function.
constexpr Dynamic Memory Allocation, C++20 constexpr has become a major feature for compile-time programming in C++. Introduced in a simple form in C++11 evolved into almost another “sub-language”, an alternative to regular template code. In C++20 you can even use std::vector and std::string in constexpr context!
P1645R1 was actually adopted in the Belfast meeting for inclusion in C++20 in response to NB comment US 320.
As a result, all of the following algorithms will be constexpr
in C++20 (except for the overloads of them that take an ExecutionPolicy
):
There is a proposal in process. We won't know the result until the process is done but it won't make C++20.
There was indeed a proposal: constexpr for algorithms, quoting the relevant part:
This proposal is to add constexpr to the following function templates in , excepting the function templates that accept an ExecutionPolicy.
- accumulate
...
We can see from the cplusplus/papers issue 432 that the paper was moved to Language Evolution Working Group:
R0, needs to be looked at / forwarded by LEWG. Removing the LWG tag.
and the milestone was moved to 2019-11
:
modified the milestones: 2019-07, 2019-11
which would be the upcomoing Belfast meeting, so it will not make C++20.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With