상세 컨텐츠

본문 제목

[C++11] decltype

C++/Modern C++(11, 14, 17, 20)

by deulee 2023. 8. 26. 16:42

본문

`decltype`은 C++11로부터 도입된 키워드로, 표현식(expression)의 결과로부터 해당 표현식의 타입을 추론해내는 데 사용된다.

 

즉, `decltype`의 특징은 다음과 같다.

 

  • 표현식의 결과로부터 해당 표현식의 타입을 추론함.

  • cv-qualifers(`const`와 `volatile`) 그리고 참조(reference)의 속성을 유지함.

그럼 다음 예시를 보도록 하자.

#include <iostream>

int main(void)
{
	int a = 1; // `a` is declared as type `int`
	decltype(a) b = a; // `decltype(a)` is `int`
	const int& c = a; // `c` is declared as type `const int&`
	decltype(c) d = a; // `decltype(c)` is `const int&`
	decltype(123) e = 123; // `decltype(123)` is `int`
	int&& f = 1; // `f` is declared as type `int&&`
	decltype(f) g = 1; // `decltype(f) is `int&&`
	decltype((a)) h = g; // `decltype((a))` is `int&`
}

여기서 의문이 들 수 있다. 왜 마지막 `decltype((a))`의 타입은 `int&`일까?

 

`decltype((a))`는 괄호로 둘러싸인 표현식 `(a)`의 타입을 나타낸다. 표현식 `(a)`는 변수 `a`"lvalue"로 취급이 된다. 이 경우 `a` `int`형 변수이므로 `decltype((a))``int&` (int 참조)타입이 된다. 변수 `g`"rvalue reference"로 선언되었지만, `decltype((a))`에서는 `a`lvalue expression을 분석하므로 이 둘 간의 호환성이 있어서 컴파일이 가능하다.

 

그리고 `decltype`는 템플릿 프로그래밍에서 유용하게 사용된다.

template <typename X, typename Y>
auto add(X x, Y y) -> decltype(x + y) {
	return x + y;
}

add(1, 2.0); // `decltype(x + y)` => `decltype(3.0)` => `double`

 

결론적으로 말하자면, `decltype`은 주어진 이름의 선언된 타입(declared type)을 돌려준다.

 

'C++ > Modern C++(11, 14, 17, 20)' 카테고리의 다른 글

[C++11] auto  (0) 2023.08.26
[C++11] Lamda Expressions  (0) 2023.08.26
[C++11] Type aliases  (0) 2023.08.26
[C++11] nullptr  (0) 2023.08.26
[C++11] Strongly-typed enums  (0) 2023.08.26

관련글 더보기