Created
April 17, 2022 06:39
-
-
Save dboyliao/15c63fb4aedd868c10af85f50a319662 to your computer and use it in GitHub Desktop.
Simple Example of Universal Reference
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> | |
#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