我正在寻找一种通过 const&
捕获的方法,甚至 const
就此而言,在可变 lambda 上。类似于下面的语法。有没有好的方法可以做到这一点?
#include <future>
#include <vector>
int main() {
std::promise<int> p;
const int N = 2;
std::vector<int> v = {1,2,3};
auto foo = [const& N, const& v, p = std::move(p)]() mutable {
v.push_back(4); // Should not compile
p.set_value(v[N]);
};
}
最佳答案
使用 std::as_const
:
#include <future>
#include <utility>
#include <vector>
int main() {
std::promise<int> p;
const int N = 2;
std::vector<int> v = {1,2,3};
auto foo = [&N, &v = std::as_const(v), p = std::move(p)]() mutable {
// v.push_back(4); // does not compile
p.set_value(v[N]);
};
}
关于c++ - 在可变 lambda 中通过常量引用捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65153819/