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.
In this code, when func is called with x, the int Lvalue version of it gets instantiated. i.e
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.
But internally, the template parameter is getting instantiated twice, once of Lvalue and the other Rvalue. The below program demonstrates it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void func(int& param) | |
{ | |
static int x = 0; | |
std::cout << "Value is " << x << '\n'; | |
++x; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void func(int&& param) | |
{ | |
static int x = 0; | |
std::cout << "Value is " << x << '\n'; | |
++x; | |
} |
Understanding universal references
Reviewed by zeroingTheDot
on
February 18, 2018
Rating:
No comments: