简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM