std::range::sort не может использоваться в качестве функции constexpr при сохранении возвращаемого значения в лямбда-функции
Эта функция f
может принимать объекты алгоритма диапазонов C++20 в качестве аргумента, а затем использовать его:
constexpr auto f(auto algo) {
return [=] {
algo(std::array{1, 0});
return true;
}();
}
и он отлично работает с std::ranges::sort
:
static_assert(f(std::ranges::sort));
Но когда я сохраняю возвращаемое значение algo
в лямбде:
constexpr auto f(auto algo) {
return [=] {
auto it = algo(std::array{1, 0});
return true;
}();
}
<source>:10:16: error: non-constant condition for static assertion
10 | static_assert(f(std::ranges::sort));
| ~^~~~~~~~~~~~~~~~~~~
<source>:10:16: error: 'constexpr auto f(auto:16) [with auto:16 = std::ranges::__sort_fn]' called in a constant expression
<source>:3:16: note: 'constexpr auto f(auto:16) [with auto:16 = std::ranges::__sort_fn]' is not usable as a 'constexpr' function because:
3 | constexpr auto f(auto algo) {
| ^
<source>:7:4: error: call to non-'constexpr' function 'f<std::ranges::__sort_fn>::<lambda()>'
4 | return [=] {
| ~~~~~
5 | auto it = algo(std::array{1, 0});
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | return true;
| ~~~~~~~~~~~~
7 | }();
| ~^~
<source>:4:10: note: 'f<std::ranges::__sort_fn>::<lambda()>' is not usable as a 'constexpr' function because:
4 | return [=] {
| ^
Почему эта функция перестает работать?constexpr
'когда я пытаюсь спасти algo
возвращаемое значение? или это просто баг?
Обновление: следующий код будет принят GCC, так что, скорее всего, это ошибка, и я уже отправил отчет об ошибке .
constexpr auto f(auto algo, auto... args) {
return [=] () mutable {
auto it = algo(args...);
return true;
}();
}
// those are ok
static_assert(f(std::ranges::reverse, std::array{0}));
static_assert(f(std::ranges::fill, std::array{0}, 0));
// those are not ok
// static_assert(f(std::ranges::sort, std::array{0}));
// static_assert(f(std::ranges::replace, std::array{0}, 0, 0));
// static_assert(f(std::ranges::unique, std::array{0}));
// static_assert(f(std::ranges::next_permutation, std::array{0}));
// static_assert(f(std::ranges::prev_permutation, std::array{0}));
1 ответ
У меня это сработает, если я объявлю итератор constexpr:
constexpr auto it = algo(std::array{1, 0});