Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Created April 17, 2022 06:39
Show Gist options
  • Save dboyliao/15c63fb4aedd868c10af85f50a319662 to your computer and use it in GitHub Desktop.
Save dboyliao/15c63fb4aedd868c10af85f50a319662 to your computer and use it in GitHub Desktop.
Simple Example of Universal Reference
#include <iostream>
#include <type_traits> // std::is_same
class Foo {
public:
Foo() = default;
Foo(const Foo &other) { std::cout << "copy!" << std::endl; }
Foo &operator=(const Foo &other) {
std::cout << "copy = !" << std::endl;
return *this;
}
Foo(Foo &&other) { std::cout << "move!" << std::endl; }
Foo &operator=(Foo &&other) {
std::cout << "move = !" << std::endl;
return *this;
}
~Foo() = default;
};
template <typename T>
void foo(T &&value) {
// IMPORTANT: `value` is a universal reference
std::cout << std::boolalpha << std::is_same<decltype(value), T &>()
<< std::endl;
}
int main(int argc, char const *argv[]) {
Foo f;
foo(f); // true, `value` is lvalue-reference to `Foo`
foo(Foo()); // false, `value` is rvalue-reference
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment