I'm looking for a way to capture by const&
, or even const
for that matter on a mutable 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
:
#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]);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With