반응형

Modern C++ auto 타입 추론(Type Deduction)

  • C++11 이상 버전에서 auto 키워드는 변수의 타입(type)을 자동으로 유추할 수 있도록 도와주지만, 개발자가 코드 내에서 실제 타입을 확인해야 하는 경우도 있습니다.
  • 예를 들어, 디버깅하거나 특정 타입에 대한 조건을 걸어야 할 때, auto가 어떤 타입으로 유추되었는지 확인하는 것이 중요합니다.
  • 이번 글에서는 auto의 실제 타입을 알아내는 여러 가지 방법을 소개하고, 각각의 방법이 출력하는 결과를 함께 살펴보겠습니다.


1. typeidtype_name 사용

  • 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
    
  • iint를 의미합니다.


  • ClangGCC에서는 c++filt로 가독성 있는 타입을 확인할 수 있습니다.
      ./a.out | c++filt -t
    
      Type of x: int
    


2. decltype 사용

  • 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__를 사용할 수 있습니다.



3. std::is_same_v 활용 (C++17)

  • 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 가 출력됩니다.



4. concepts 활용 (C++20)

  • C++20concepts 기능을 활용하면 더욱 직관적으로 타입을 분류할 수 있습니다.

  • 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.0ffloat이므로 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
반응형

+ Recent posts