원어로는 declaration type으로, 컴파일 타임에 지정된 식의 형식을 생성합니다.
즉, 타입을 명시하지 않고도 자동으로 추론할 수 있는 매우 강력한 도구입니다.
가벼운 예시
int x = 10;
decltype(x) y = 20; // decltype(x)는 int입니다.
여기까지만 보면 auto와 차이가 없어보입니다.
하지만 auto는 변수의 값을 기반으로 형식을 결정합니다.
decltype는 표현식을 기반으로 타입을 결정하기 때문에 상수성(const)와 참조(reference), 포인터(pointer)를 모두 포함하여 형식을 추론합니다.
int a = 10;
int& b = a;
const int c = 50;
auto aa = a; // aa is of type int
auto ab = b; // ab is of type int
auto ac = c; // ac is of type int
decltype(a) da = 1; // da is of type int
decltype(b) db = da; // db is of type int& (참조 유지)
decltype(c) dc = 2; // dc is of type const int (상수성 유지)
C++14에서 새롭게 추가된 기능으로 decltype을 사용하면서도, 반환 값이나 변수의 타입으로 자동으로 결정하고 싶을 때 유용합니다.
가벼운 예시
int a = 10;
int& b = a;
const int c = 50;
decltype(auto) da = a; // da is of type int
decltype(auto) db = b; // db is of type const int (상수성 유지)
decltype(auto) dc = c; // dc is of type int& (참조 유지)