cref.cpp

The following code example is taken from the book
C++ Templates - The Complete Guide, 2nd Edition
by David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor,
Addison-Wesley, 2017
© Copyright David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor 2017


#include <functional>  // for std::cref()
#include <string>
#include <iostream>

void printString(std::string const& s)
{
  std::cout << s << '\n';
}

template<typename T>
void printT (T arg)
{
  printString(arg);        // might convert arg back to std::string
}

int main()
{
  std::string s = "hello";
  printT(s);               // print s passed by value
  printT(std::cref(s));    // print s passed ``as if by reference''
}