Type Deduction이 발생하는 경우

template과 auto는 동일한 규칙을 사용한다.

Type Deduction 예

template<class T> void Foo(T arg){}
template<class T> void Foo2(T& arg){}

int& Goo(int a, int b) { ... }

void main()
{
	int n = 10;
	int& r = n;
	int* p = &n;
	const int c = 10;
	const int& cr = c;

	// 함수 인자의 const, volatile, reference를 제거하고 T의 타입을 결정한다.
	Foo(n); // T=int
	Foo(r); // T=int
	Foo(c); // T=int
	Foo(cr); // T=int

	// 인자가 가리키는 곳의 const 속성은 유지 된다.
	const char* const s = "hello";
	Foo(s); // T=const char* 

	// 함수 인자의 reference를 제거하고, T의 타입을 결정한다.
	// 인자가 가진 const, volatile 속성은 유지.
	Foo2(n); // T=int, arg=int&
	Foo2(r); // T=int, arg=int&
	Foo2(c); // T=const int, arg=const int&
	Foo2(cr); // T=const int, arg=const int&

	// 배열.
	int x[3] = {1, 2, 3};
	Foo(x); // T=int*
	Foo2(x); // T=int(&)[3]

	decltype(n) d1; // int
	decltype(r) d2; // int& d2 초기화문제 error
	decltype(p) d3; // int* d3
	decltype(c) d4; // const int d4 초기화문제 error
	decltype(cr) d5; // const int& d5 초가화문제 error

	// auto 위치에 우변 표현식을 넣어서 타입 추론.
  // 즉, 우변 표현식으로 타입을 추론하는데, 규칙은 decltype 규칙 사용
	// C++ 14부터 사용가능.
	decltype(auto) ret = Goo(1, 2);
}

template<class T1, class T2>
// decltype(a+b) Add(T1 a, T2 b) // error a, b 가 선언 되기 전에 사용했기에.
// decltype(auto) Add(T1 a, T2 b) // 아래 방식과 동일. (C++14)
auto Add(T1 a, T2 b) -> decltype(a+b) // suffix return, (C++11)
{
	...
}

주의점