[英]Capturing by const reference in mutable lambda
I'm looking for a way to capture by const&
, or even const
for that matter on a mutable lambda.我正在寻找一种通过
const&
捕获的方法,甚至是const
在可变 lambda 上的捕获方法。 Something like the syntax below.类似于下面的语法。 Is there a good way to do this?
有没有好的方法来做到这一点?
#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]);
};
}
Use std::as_const
:使用
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]);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.