std::reference_wrapper
wraps a reference in a copyable, assignable object.
std::reference_wrapper
is a class template that wraps a reference in a copyable, assignable object.
It is defined in header <functional>
.
Specifically, std::reference_wrapper
is a CopyConstructible
and CopyAssignable
wrapper around a reference to 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.
std::reference_wrapper
is used to pass objects by reference to std::bind
, the constructor of std::thread
, or the helper functions std::make_pair
and std::make_tuple
. It can also be used as a mechanism to store references inside standard containers (like std::vector
) that cannot normally hold references.
std::reference_wrapper
is guaranteed to be TriviallyCopyable. (since C++17)
T
may be an incomplete type. (since C++20)
type
: member type, defined as T
.
Public member functions:
(constructor) | stores a reference in a new std::reference_wrapper object |
operator= | rebinds a std::reference_wrapper |
get | accesses the stored reference |
operator T& | accesses the stored reference |
operator() | calls the stored function |
Non-member functions (C++26):
operator== (C++26) | compares reference_wrapper objects as their stored references |
operator<=> (C++26) | compares reference_wrapper objects as their stored references |
Examples
Demonstrates the use of std::reference_wrapper as a container of references, which makes it possible to access the same container using multiple indices.
#include <algorithm> #include <functional> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> void println(auto const rem, std::ranges::range auto const& v) { for (std::cout << rem; auto const& e : v) std::cout << e << ' '; std::cout << '\n'; } int main() { std::list<int> l(10); std::iota(l.begin(), l.end(), -4); // can't use shuffle on a list (requires random access), but can use it on a vector std::vector<std::reference_wrapper<int>> v(l.begin(), l.end()); std::ranges::shuffle(v, std::mt19937{std::random_device{}()}); println("Contents of the list: ", l); println("Contents of the list, as seen through a shuffled vector: ", v); std::cout << "Doubling the values in the initial list...\n"; std::ranges::for_each(l, [](int& i) { i *= 2; }); println("Contents of the list, as seen through a shuffled vector: ", v); }
Demonstrates...
[...]
std::ref
and std::cref
(C++11)
Function templates ref()
and cref()
are helper functions that generate an object of type std::reference_wrapper, using template argument deduction to determine the template argument of the result.
They are defined in header <functional>
.
Prototypes (since C++11 , and constexpr
since C++20)
template< class T > std::reference_wrapper<T> ref( T& t ) noexcept; template< class T > std::reference_wrapper<T> ref( std::reference_wrapper<T> t ) noexcept; template< class T > void ref( const T& ) = delete; template< class T > std::reference_wrapper<const T> cref( const T& t ) noexcept; template< class T > std::reference_wrapper<const T> cref( std::reference_wrapper<T> t ) noexcept; template< class T > void cref( const T& ) = delete;
Example:
Another example:
std::function
The std::function() in C++ is a function wrapper class which can store and call any function or a callable object.
It is defined in header <functional>
std::function
is a template class in C++ that is used to wrap a particular function or any other callable object such as a lambda, or function object. It is generally used to write generic code where we need to pass functions as arguments in another function (callbacks). It avoids the creation of extra overloads of the function that may take similar callback functions as arguments.
std::function
is defined in the <functional>
header file.
To create a wrapper object, we first declare it using the following syntax:
std::function< rtype (atype...)> name();
where,
- name: Name of the wrapper.
- atype: Types of the arguments that function takes.
- rtype: Return type of the function you want to store.
The above syntax only creates an empty instance of std::function
. To wrap a particular function inside this wrapper object, we use assignment operator as shown:
std::function< ret_t (args_t)> name = f;
where f is the function to be wrapped.
We can also initialize it at the time of declaration:
std::function< ret_t (args_t)> name(f);
Example of std::function
// C++ Program to illustrate the working // std::function #include <bits/stdc++.h> using namespace std; int f(int a, int b) { return a + b; } int main() { // std::function wrapping traditional // function function<int(int, int)> calc = f; cout << "Sum: " << calc(8, 2) << endl; // std::function wrapping a lambda // expression calc = [](int a, int b) { return a * b; }; cout << "Product: " << calc(8, 2); return 0; }
Member Functions of std::function
std::function
contains some member functions to provide some basic functionality. The following table lists some useful member functions of std::function
class template:
Function | Description |
swap() | Swaps the wrapped callable of two std::function objects. |
operator bool | Checks if the std::function contains a callable. |
operator () | Invoke the callable with the given arguments. |
target() | Returns a pointer to the stored callable. If there is no callable stored, returns nullptr . |
target_type() | Returns the typeid of the callable. If no callable is stored, it returns typeid(void) . |
Applications of std::function
's in C++
Apart from the applications shown in the above examples, std::function
can also be used for:
- Callbacks: Used for event-driven systems where functions are passed and called later when an event occurs.
- Function Wrapping and Higher-Order Functions: Allows passing functions as parameters and returning them. :
- Stateful Callbacks: Enables callbacks with preserved states, making it easier to manage state without global variables.
- Replacing Function Pointers: Provides a safer and more flexible alternative to traditional function pointers, supporting multiple callable types.