简体   繁体   English

通过可变 lambda 中的 const 引用捕获

[英]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.

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