[Modern C++] Type Deduction - auto

Program Lang./C++ 2019. 7. 29. 10:37

1. auto type deduction

 

auto와 template의 type deduction 과정은 braced initalizer에 대한 type deduction을 제외하고는 동일하다.

 

braced initalizer에 대한 auto와 template의 기본 동작은 아래와 같다.

  • auto
    • std::initializer_list로 type deduction 된다.
  • template
    • std::initializer_list로 type deduction을 지원하지 않는다.

 

auto에 대한 위의 braced initalizer 기본 동작이 아래와 같은 경우에 또 예외 동작을 수행한다.

  • auto가 함수의 return type으로 사용 시
    • template처럼 동작한다. 즉 std::initializer_list로 type deduction되지 않는다.
  • lambda의 매개변수에 사용 시
    • template처럼 동작한다.

다음절에서 위에서 기술한 기본동작과 예외 동작에 대해서 상세하게 알아본다.

 

2. auto 기본동작 (template와 동일)

 

auto type specifier template Result
auto x = 27;

template<typename T> void f(T param);

f(27);

T : int,

int x = 27;

const auto cx = x;

template<typename T> void f(const T param);

f(x);

T : int,

const int cx = x;

const auto& rx = x;

template<typename T> void f(const T& param);

f(x);

T : int,

const int& rx = x;

auto&& fr = x;

template<typename T> void f(T&& param);

f(x);

x : int 이고 lvalue,

int& fr = x;

auto&& fr = cx;

template<typename T> void f(T&& param);

f(cx);

cx : const int 이고 lvalue,

const int& fr = cx;

auto&& fr = 27

template<typename T> void f(T&& param);

f(27);

27 : int이고  rvalue,

int&& = 27

const char name[] = "heesoon.kim";

auto ar = name;

template<typename T> void f(T param);

f(name);

name : const char[13],

const char* ar = name;

const char name[] = "heesoon.kim";

auto& ar = name;

template<typename T> void f(T& param);

f(name);

name : const char[13],

const char(&) ar = name;

void function(int, double);

auto fp = function;

template<typename T> void f(T param);

f(function);

function : void(*)(int, double),

void(*fp)(int, double) = function;

void function(int, double);

auto& fp = function;

template<typename T> void f(T& param);

f(function);

function : void(*)(int, double),

void(&fp)(int, double) = function;

 

3. auto 와 template의 braced intializer와의 기본동작

 

서두에 기술한 auto와 template의 braced initializer에 대한 동작 차이점을 보여주는 예제이다.

 

 

4. braced intializer와 auto의 기본동작의 예외 케이스

 

서두에 기술한 auto와 template의 braced initializer에 대한 동작 차이점을 보여주는 예제이다.

 

 

5. 정리

 

auto의 type deduction 동작은 template와 동일하다. 다만 braced initializer와의 동작에 대해서는

auto와 template간의 차이가 있고, 그 경우에 대해서 정리했다.

'Program Lang. > C++' 카테고리의 다른 글

[Modern C++] reference collapsing  (0) 2019.07.31
[Modern C++] Type Deduction - decltype  (0) 2019.07.29
[Modern C++] Type Deduction - Template  (0) 2019.07.28
[Basic] Object Generator  (0) 2017.07.09
boost asio 정리 - 5 (work 고찰)  (0) 2017.05.12
: