-
Notifications
You must be signed in to change notification settings - Fork 62
Description
Standard constexpr algorithms
P0202 proposes to add constepxr to many functions from <cstring> and to basically every algorithm from <algorithm>. Apparently, the proposal was rather well-received and we might have constexpr algorithms in the standard at some point in the future.
So, what about cpp-sort? Since we're already using C++14, we can use the improved constexpr but I feel that it won't solve every problem:
std::swapand a few other utility functions are notconstexpr, but we could probably reimplement a few of them. Update: actually, some parts of<functional>such asstd::mem_fnand a good part of<iterator>would have to be reimplemented too in order to handle everything, and some parts are rather huge.- The standard algorithms are not
constexpreither, but since we ship altered versions of many of them, addingconstexprshouldn't be a problem. - Some algorithms allocate dynamic memory. There is currently no way I know of to solve this problem. Projects reimplementing a
constexprversion of the standard algorithms such as Bolero Murakami's Sprout don't use algorithms that allocate heap memory; these projects are generally only meant to be used at compile-time.
I would be trivial to change some algorithms to be constexpr but it's probably not the case for most of them. A partial constexpr support could be a starting point.
The first revision of P0202 takes several design choices into consideration and gives the following set of rules to make standard algorithms constexpr (<cstring> has been disqualified from constexpr enhancements):
- For some of them, most notably the non-mutating ones, just adding
constexprshould be enough. - Some of them rely on
std::memcpyand friends, so compilers are encouraged to use their own equivalentconstexprintrinsics of these functions instead. It concerns everything that relies on thestd::copyandstd::movefamily of algorithms. - Algorithms that might allocate heap memory such as
std::stable_partitionandstd::stable_sortare not markedconstexpr.
Basically, we will wait for a constexpr-ified standard library (at least for std::copy and std::move), then we can start to constexpr-ify cpp-sort. The whole iter_move thing might make things harder to do though. Anyway, this is definitely a future issue.
Use cases
I often wondered whether there were use cases for constexpr sorting algorithms. Here is a list of situations where sorting at compile-time might be useful:
- Compile-time
std::setwhich sorts its input and performs a binary search on lookup, which is more performant than the tree implementation (e.g. Frozen). - It can be used to reorder struct fields by size to make tighter structs.
- Other ideas?
Metadata
Metadata
Assignees
Projects
Status