Understanding universal references

As we discussed in the previous article, && means universal references when type deduction is involved.
But internally, the template parameter is getting instantiated twice, once of Lvalue and the other Rvalue. The below program demonstrates it.

#include <iostream>
template<typename T>
void func(T&& param)
{
static int x = 0;
std::cout << "Value is " << x << '\n';
++x;
}
int main()
{
int x = 2;
func(x);
func(2);
func(x);
func(2);
}
/* Output
Value is 0
Value is 0
Value is 1
Value is 1
*/

In this code, when func is called with x, the int Lvalue version of it gets instantiated.  i.e

void func(int& param)
{
static int x = 0;
std::cout << "Value is " << x << '\n';
++x;
}
When func is called the second time with 2, the int Rvalue version of it gets instantiated (see code below). Hence the value count is 0 in both the cases.
void func(int&& param)
{
static int x = 0;
std::cout << "Value is " << x << '\n';
++x;
}
Understanding universal references Understanding universal references Reviewed by zeroingTheDot on February 18, 2018 Rating: 5

No comments:

Powered by Blogger.