C++ Utility::forward() Function



The C++ std::utility::forward() function is designed to enable perfect forwarding of arguments. It allows you to preserve the value category (rvalue or lvalue) of the arguments passed to a function.

For example, if we use std::forward<T>(arg), where T is a rvalue, then it is forwarded as rvalue or viceversa.

Syntax

Following is the syntax for std::utility::forward() function.

forward (typename remove_reference<T>::type& arg) noexcept; or forward (typename remove_reference<T>::type&& arg) noexcept;

Parameters

  • arg − It indicates an object.

Return Value

It returns an rvalue reference to arg if arg is not an lvalue reference.

Exceptions

This function never throws exceptions.

Data races

none

Example 1

In the following example, we are going to consider the basic usage of the forward() function.

#include <iostream> #include <utility> void a(int & x) { std::cout << "Lvalue : " << x << std::endl; } void a(int && x) { std::cout << "Rvalue : " << x << std::endl; } template < typename T > void y(T && arg) { a(std::forward < T > (arg)); } int main() { int a = 11; y(a); y(2); return 0; }

Output

Output of the above code is as follows −

Lvalue : 11
Rvalue : 2
utility.htm
Advertisements