我正在尝试将 lambda 应用于 std::array 的元素。
std::array<int, 4> fixIndices = {1, 60, 127, 187};
std::apply(
[](int id) {
std::cout << id;
},
fixIndices);
但是,这个简单的代码无法编译
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/c++/tuple:1727:27: error: no matching function for call to ‘__invoke(****)::<lambda(int)>, int&, int&, int&, int&)’
1727 | return std::__invoke(std::forward<_Fn>(__f),
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
1728 | std::get<_Idx>(std::forward<_Tuple>(__t))...);
我错过了什么?
最佳答案
std::apply
将元组中包含的参数(类似)转发给可调用的 f
,因此您的 lambda 应该是
std::array<int, 4> fixIndices = {1, 60, 127, 187};
std::apply(
[](auto... ids) {
((std::cout << ids << " "), ...);
},
fixIndices);
但对于 std::array
,如果您想遍历它的元素,基于范围的 for 循环是一个更简单的选择。
https://stackoverflow.com/questions/72025515/