Last active
August 29, 2015 14:20
-
-
Save gnarayan81/41c521400e8251748cff to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//---------------------------------------------------------------------- | |
// Type deduction class. | |
struct s_td { // Do not make this a class template, unless the template | |
// is necessary for something other than echoval(...) | |
template <typename K> | |
void echoval(K&& t) // Universal reference. | |
{ | |
std::cout << "t = " << t << '\n'; | |
} | |
}; | |
//---------------------------------------------------------------------- | |
// Universal type deduction. | |
void universal_type_deduction(void) | |
{ | |
// Trivially, | |
int x = 42; | |
int& l_rx = x; // fine | |
int&& r_rx1 = 42; // fine | |
//int&& r_rx2 = x; // I know it will fail compile here. | |
auto&& r_rx3 = 42; // fine, rvalue | |
auto&& r_rx4 = x; // fine, type-deduced! Universal. | |
auto&& r_rx5 = l_rx; // fine, type-deduced! Universal. | |
s_td().echoval(42); // Do not specialize! | |
s_td().echoval(x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gcc users compile with -std=c++11
This snippet illustrates briefly the concept of universal references, as defined by Scott Meyers. Note that this kind of universality of reference is true of templates as well.