Updated:

less than 1 minute read

개요

  • l-value는 l-value로 r-value는 r-value로 전달해야하는 경우
  • wrapper 형태의 경우 r-value를 인자로 전달하면 변수 자체는 l-value이므로 l-value 함수가 호출
  • move를 사용하면 l-value도 r-value로 변환이 되므로 사용할 수 없음


코드

#include <iostream>

using namespace std;

void func(int &i) { cout << "func(int &i)" << endl; }
void func(const int &i) { cout << "func(const int &i)" << endl; }
void func(int &&i) { cout << "func(int &&i)" << endl; }

template <typename T> void wrapper1(T &&t) { func(t); }

template <typename T> void wrapper2(T &&t) { func(forward<T>(t)); }

int main() {
    int i1 = 1;
    const int i2 = 2;

    wrapper1(i1);
    wrapper2(i1);
    cout << "------" << endl;
    wrapper1(i2);
    wrapper2(i2);
    cout << "------" << endl;
    wrapper1(3);
    wrapper2(3);

    return 0;
}


실행 결과

func(int &i)
func(int &i)
------
func(const int &i)
func(const int &i)
------
func(int &i)
func(int &&i)