lang/forwardlike.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 <vector>
#include <utility>  // for std::forward_like<>()

template<typename CollT>
void insertElemsInto(CollT&& coll, auto& dst)
{
  for (auto&& elem : coll) {
    dst.push_back(std::forward_like<CollT>(elem));  // copies or moves acc. to coll
  }
}

void debugColl(const std::vector<std::string>& coll, const std::string& name)
{
  std::println("{}:", name);
  for (const auto& s : coll) {
    std::println("  [{1}: {0}]", s, static_cast<const void*>(s.data()));
  }
}

int main()
{
  std::vector<std::string> coll{"string1withSignificantSize",
                                "string2withSignificantSize"};
  debugColl(coll, "coll");

  std::vector<std::string> dest;

  insertElemsInto(coll, dest);             // copy elements of coll into dest
  insertElemsInto(std::move(coll), dest);  // move elements of coll into dest

  debugColl(coll, "coll after copy and move");
  debugColl(dest, "dest after copy and move");
}