在可变 lambda 中通过常量引用捕获

Kos*_*tas 4 c++ lambda

我正在寻找一种方法来捕获 by const&,甚至const在可变 lambda 上。类似于下面的语法。有没有好的方法可以做到这一点?

#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]);
  };
}
Run Code Online (Sandbox Code Playgroud)

HTN*_*TNW 7

使用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]);
  };
}
Run Code Online (Sandbox Code Playgroud)