15
Effective Modern C++ Study C++ Korea

[C++ korea] effective modern c++ study item 2 understanding auto type deduction +옥찬호

Embed Size (px)

Citation preview

Effective Modern C++ Study C++ Korea

Effective Modern C++ Study C++ Korea 3

template<typename T>

void f(Paramtype param);

f(expr);

템플릿 타입 추론

auto x = 27;

const auto cx = x;

const auto& rx = x;

auto 타입 추론

직접 매핑 (Direct Mapping)

Effective Modern C++ Study C++ Korea 4

template<typename T>

void func_for_x(T param);

func_for_x(27);

template<typename T>

void func_for_cx(const T param);

func_for_cx(x);

template<typename T>

void func_for_rx(const T& param);

func_for_rx(x);

auto x = 27; (타입 지정자 : auto)

const auto cx = x; (타입 지정자 : const auto)

const auto& rx = x; (타입 지정자 : const auto&)

Effective Modern C++ Study C++ Korea 5

Effective Modern C++ Study C++ Korea 6

auto x = 27; // 경우 3 // x는 포인터 또는 레퍼런스가 아님 // 경우 3 // cx는 포인터 또는 레퍼런스가 아님 // 경우 1 // rx는 유니버셜 레퍼런스가 아닌 레퍼런스임

const auto cx = x;

const auto& rx = x;

Effective Modern C++ Study C++ Korea 7

auto&& uref1 = x; // x는 int이며 Lvalue // 따라서 uref1의 타입은 int& // x는 const int이며 Lvalue // 따라서 uref2의 타입은 const int& // 27은 int이며 Rvalue // 따라서 uref3의 타입은 int&&

auto&& uref2 = cx;

auto&& uref3 = 27;

Effective Modern C++ Study C++ Korea 8

Effective Modern C++ Study C++ Korea 9

Effective Modern C++ Study C++ Korea 10

Effective Modern C++ Study C++ Korea 11

auto x = {11, 23, 9};

template<typename T>

void f(T param);

// x의 타입은 std::initializer_list<int>

// 매개변수가 있는 템플릿의 선언은 // x의 선언와 동일함

f({11, 23, 9}); // 오류! T의 타입을 추론할 수 없음

Effective Modern C++ Study C++ Korea 12

template<typename T>

void f(std::initializer_list<T> initList);

f({11, 23, 9}); // T는 int로 추론 // initList의 타입은 std::initializer_list<int>

Effective Modern C++ Study C++ Korea 13

auto createInitList()

{

return {1, 2, 3};

}

// 오류 : 타입을 추론할 수 없음

Effective Modern C++ Study C++ Korea 14

std::vector<int> v;

auto resetV =

[&v](const auto& newValue) { v = newValue; };

resetV({1, 2, 3}); // 오류 : 타입을 추론할 수 없음

Effective Modern C++ Study C++ Korea 15