reference_wrapper in C++


In C++ the reference_wrapper is a class template that helps by wrapping a reference in a copy constructible and copy assignable object of type T. The instances of std::reference_wrapper are basically objects, but they can be converted into T&. So we can use as argument with the functions that take the underlying type by reference.

Example Code

#include <iostream>
#include <functional>
using namespace std;
int main () {
   char a = 'h', b = 'e', c = 'l', d = 'l', e = 'o' , f = 'W', g = 'o', h = 'r', i = 'l', j = 'd';
   reference_wrapper<char> ref[] = {a, b, c, d, e, f, g, h, i, j}; //creating reference array
   for (char& s : ref)
      cout << s;
   cout <<endl;
   return 0;
}

Output

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
helloWorld
soumyadeep@soumyadeep-VirtualBox:~$

Updated on: 30-Jul-2019

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements