reference_wrapper in C++

std::reference_wrapper is a class template that wraps a reference in a copy constructible and copy assignable object or reference to function of type T.
Instances of std::reference_wrapper are objects (they can be copied or stored in containers) but they are implicitly convertible to ‘T&’ so that they can be used as arguments with the functions that take the underlying type by reference.

Syntax:

template <class T> class reference_wrapper;
template parameter(T): type of the referred element and
                        this can be  either function or object.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate the
// use of std::reference_wrapper
#include <iostream>    
#include <functional> 
using namespace std;
  
int main () 
{
    char a = 'g', b = 'e', c  = 'e', d = 'k', e = 's';
      
    // creating an array of character "references":
    reference_wrapper<char> ref[] = {a, b, c, d, e};
      
    for (char& s : ref)
          cout << s;
      
    return 0;
}

chevron_right


Output:

ref:geeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.