Skip to content

Instantly share code, notes, and snippets.

@gnarayan81
Last active August 29, 2015 14:20
Show Gist options
  • Save gnarayan81/41c521400e8251748cff to your computer and use it in GitHub Desktop.
Save gnarayan81/41c521400e8251748cff to your computer and use it in GitHub Desktop.
//----------------------------------------------------------------------
// 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);
}
@gnarayan81
Copy link
Author

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.

  • Note that when an rvalue is passed into a function / method, it WILL become an lvalue, since it has storage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment