此函数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
但是当我在 lambda 中保存返回值时:
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}));