Kostas
Kostas

Reputation: 4176

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. 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]);
  };
}

Upvotes: 4

Views: 206

Answers (1)

HTNW
HTNW

Reputation: 29193

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]);
  };
}

Upvotes: 7

Related Questions