Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing by const reference in mutable lambda

Tags:

c++

lambda

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]);
  };
}
like image 429
Kostas Avatar asked Mar 01 '23 21:03

Kostas


1 Answers

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]);
  };
}
like image 137
HTNW Avatar answered Mar 06 '23 06:03

HTNW