lang/forwardcapture.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <print>
#include <string>
#include <vector>
#include <utility>  // for forward_like<>()

int main()
{
  std::vector<std::string> coll;

  std::string dat("stringWithSignificantSize");
  std::println("dat: [{}: {}]", static_cast<const void*>(dat.data()), dat);

  // init a lambda that can copy or move captured data:
  auto capturedDataInto = [&dat] (this auto&& self, auto& coll) {
    coll.push_back(std::forward_like<decltype(self)>(dat));
  };

  capturedDataInto(coll);               // copy captured data into coll
  std::move(capturedDataInto)(coll);    // move captured data into coll

  std::println("dat: [{}: {}]", static_cast<const void*>(dat.data()), dat);
  std::println("coll:");
  for (const auto& elem : coll) {
    std::println("  [{}: {}]", static_cast<const void*>(elem.data()), elem);
  }
}