반응형
C++11
이상 버전에서auto
키워드는 변수의 타입(type
)을 자동으로 유추할 수 있도록 도와주지만, 개발자가 코드 내에서 실제 타입을 확인해야 하는 경우도 있습니다.- 예를 들어, 디버깅하거나 특정 타입에 대한 조건을 걸어야 할 때,
auto
가 어떤 타입으로 유추되었는지 확인하는 것이 중요합니다. - 이번 글에서는
auto
의 실제 타입을 알아내는 여러 가지 방법을 소개하고, 각각의 방법이 출력하는 결과를 함께 살펴보겠습니다.
-
cpp
#include <iostream> #include <typeinfo> int main() { auto x = 42; // int std::cout << "Type of x: " << typeid(x).name() << std::endl; return 0; }
-
output
Type of x: i
-
i
는int
를 의미합니다.
Clang
과GCC
에서는c++filt
로 가독성 있는 타입을 확인할 수 있습니다../a.out | c++filt -t
Type of x: int
-
decltype
을 사용하면auto
로 유추된 변수의 타입을 템플릿 함수에서 확인할 수 있습니다. -
cpp
#include <iostream> template <typename T> void print_type() { #ifdef _MSC_VER std::cout << __FUNCSIG__ << std::endl; // MSVC 전용 #else std::cout << __PRETTY_FUNCTION__ << std::endl; // GCC/Clang 전용 #endif } int main() { auto x = 3.14; // double print_type<decltype(x)>(); return 0; }
-
output (
GCC
기준)void print_type() [with T = double]
-
T = double
이므로x
의 실제 타입은double
임을 알 수 있습니다. -
Clang
에서도 비슷한 결과를 출력합니다. -
MSVC
에서는__PRETTY_FUNCTION__
대신__FUNCSIG__
를 사용할 수 있습니다.
-
C++17
부터 지원하는std::is_same_v
를 사용하면 특정 타입과 비교하여 타입을 판별할 수 있습니다. -
cpp
#include <iostream> #include <type_traits> int main() { auto x = 42; if constexpr (std::is_same_v<decltype(x), int>) { std::cout << "x is int\n"; } else if constexpr (std::is_same_v<decltype(x), double>) { std::cout << "x is double\n"; } return 0; }
-
output
x is int
-
decltype(x) == int
이므로x is int
가 출력됩니다.
-
C++20
의concepts
기능을 활용하면 더욱 직관적으로 타입을 분류할 수 있습니다. -
cpp
#include <iostream> #include <concepts> template <typename T> void print_type(T) { if constexpr (std::integral<T>) { std::cout << "Integral type\n"; } else if constexpr (std::floating_point<T>) { std::cout << "Floating-point type\n"; } } int main() { auto x = 42.0f; // float print_type(x); return 0; }
-
output
Floating-point type
-
x = 42.0f
는float
이므로Floating-point type
이 출력됩니다.
-
방법 결과 typeid(x).name()
i
(int
),d
(double
) 등 (컴파일러마다 다름)decltype
T = int
,T = double
등 출력std::is_same_v
x is int
또는x is double
concepts
Integral type
또는Floating-point type
- 빠르고 간단한 방법 :
typeid(x).name()
- 가독성이 좋은 방법 :
decltype
,std::is_same_v
- 최신 방법 :
concepts
- 개발 환경과 필요에 따라 적절한 방법을 선택하여
auto
의 실제 타입을 확인하면 됩니다! 🚀🛸
728x90
반응형
'C C++' 카테고리의 다른 글
C++11 : Modern C++의 시작 (0) | 2025.03.07 |
---|---|
overload.cpp : C++17 방문자 패턴(visitor pattern) 오버로딩 (0) | 2025.03.06 |
Modern C++을 활용한 Python itertools 스타일의 반복자 구현 (0) | 2025.03.06 |
Modern C++ 의 std::visit 와 std::variant 가이드 (0) | 2025.03.04 |
Modern C++ std::apply 사용법 및 예제 (0) | 2025.03.04 |