![]() |
VOOZH | about |
In C++, std::forward() is a template function used for achieving perfect forwarding of arguments to functions so that it's lvalue or rvalue is preserved. It basically forwards the argument while preserving the value type of it.
std::forward() was introduced in C++ 11 as the part of <utility> header file.
std::forward<T> (arg)
where,
Process lvalue: 10 Process rvlaue: 10
Explanation:
Here, in function fun(), T&& is called as universal reference which means it can hold both type (lvalue and rvalue). By using std::forward(), it will check what type is coming in arg. Based on whether it is lvalue or rvalue, it will call the correct overloaded version of the utilityFun().
If we don't use std::forward, it will every time call lvalue version of utilityFun(int &i), as compiler won't check the type of arg and assumed that it is lvalue only, which we will see in below example.
Process lvalue: 10 Process lvalue: 10
In the above program,