[C++] 보편 참조
Updated:
개요
- 변수(auto &&)나 인자(템플릿 인자 - T &&)가 r-value reference(&&) 형태이며 타입 추론이 필요한 레퍼런스
- 형태는 r-value reference지만 실제 의미는 l-value reference일 수도 있는 레퍼런스
- l-value도 인자로 받을 수 있음
- 타입 추론
- & &는 &
- & &&는 &
- && &는 &
- && &&는 &&
예제
- 코드
#include <iostream> using namespace std; void func(int &i) { cout << "func(int &i)" << endl; } void func(int &&i) { cout << "func(int &&i)" << endl; } template <typename T> void wrapper0(T &&t) { func(t); }; template <typename T> void wrapper1(T &&t) { func(forward<decltype(t)>(t)); }; template <typename T> void wrapper2(T &&t) { func(forward<T>(t)); } int main() { int i = 0; int &lri = i; wrapper0(i); wrapper1(i); wrapper2(i); cout << "------" << endl; wrapper0(move(i)); wrapper1(move(i)); wrapper2(move(i)); cout << "------" << endl; wrapper0(lri); wrapper1(lri); wrapper2(lri); cout << "------" << endl; wrapper0(0); wrapper1(0); wrapper2(0); return 0; }
- 실행 결과
func(int &i) func(int &i) func(int &i) ------ func(int &i) func(int &&i) func(int &&i) ------ func(int &i) func(int &i) func(int &i) ------ func(int &i) func(int &&i) func(int &&i)