'C++' common_type_t

토스트·2025년 5월 2일
0

'C++' basic

목록 보기
25/35

<type_traits>

common_type_t

C++ 표준 라이브러리에서 여러 타입의 공통 타입(common type)을 컴파일 타입에 계산하는 유틸리티입니다.

여러 타입이 있을 때, 이들을 암시적으로 변환할 수 있는 하나의 공통 타입을 찾아주는 메타 함수입니다.

암시적 형 변환(implicit type conversion)을 가시적으로 보여주는 역할을 합니다.

간단한 예시

#include <type_traits>

std::common_type_t<int, double> x = 3.14; // x는 double;

활용

#include <iostream>
#include <type_traits>

using namespace std;

template<typename T1, typename T2>
common_type_t<T1, T2> gcd(T1 a, T2 b) {
    using CT = common_type_t<T1, T2>; // Common Type : long long
    CT x = a;
    CT y = b;

    while (y != 0) {
        CT temp = y;
        y = x % y;
        x = temp;
    }

    return x;
}

int main() {
    cout << gcd(1234567890, 9876543210LL); // T1 : int, T2 : long long

    return 0;
}

0개의 댓글