Namespaces
Variants

std:: common_type

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

common_type
(C++11)
(C++11)
(C++17)
Compile-time rational arithmetic
Compile-time integer sequences
헤더 파일에 정의됨 <type_traits>
template < class ... T >
struct common_type ;
(C++11부터)

모든 타입 T... 중 공통 타입을 결정합니다. 즉, 모든 T... 가 명시적으로 변환될 수 있는 타입입니다. 그러한 타입이 존재하는 경우(아래 규칙에 따라 결정됨), 멤버 type 은 해당 타입을 지정합니다. 그렇지 않으면 멤버 type 이 존재하지 않습니다.

  • 만약 sizeof... ( T ) 이 0이면, type 멤버가 존재하지 않습니다.
  • 만약 sizeof... ( T ) 이 1이면 (즉, T... 이 단 하나의 타입 T0 만을 포함하는 경우), 멤버 type std :: common_type < T0, T0 > :: type 와 동일한 타입을 나타냅니다 (해당 타입이 존재하는 경우). 그렇지 않으면 type 멤버가 존재하지 않습니다.
  • 만약 sizeof... ( T ) 이 2이면 (즉, T... 이 정확히 두 개의 타입 T1 T2 를 포함하는 경우),
  • T1 T2 중 적어도 하나에 std::decay 를 적용했을 때 다른 타입이 생성된다면, 멤버 type std :: common_type < std:: decay < T1 > :: type , std:: decay < T2 > :: type > :: type 와 동일한 타입을 나타내며, 해당 타입이 존재하지 않으면 멤버 type 이 존재하지 않습니다;
  • 그렇지 않고 std :: common_type < T1, T2 > 에 대한 사용자 특수화가 존재하면 해당 특수화가 사용됩니다;
  • 그렇지 않고 std:: decay < decltype ( false ? std:: declval < T1 > ( ) : std:: declval < T2 > ( ) ) > :: type 가 유효한 타입이라면, 멤버 type 은 해당 타입을 나타내며, 자세한 내용은 조건 연산자 를 참조하십시오;
(C++20부터)
  • 그렇지 않으면, 멤버 type 이 존재하지 않습니다.
  • 만약 sizeof... ( T ) 이 2보다 크면 (즉, T... T1, T2, R... 타입들로 구성된 경우), std :: common_type < T1, T2 > :: type 이 존재할 때, 멤버 type std :: common_type < typename std :: common_type < T1, T2 > :: type , R... > :: type 을 나타냅니다. 다른 모든 경우에는 type 멤버가 존재하지 않습니다.

매개변수 팩 T 내의 어떤 타입이 완전한 타입이 아니거나, (cv-qualified일 수 있는) void , 또는 unknown bound의 배열인 경우, 그 동작은 정의되지 않습니다.

템플릿의 인스턴스화가 직접적 또는 간접적으로 불완전한 타입에 의존하고, 해당 타입이 가상적으로 완성되었을 때 인스턴스화 결과가 달라질 수 있는 경우, 그 동작은 정의되지 않습니다.

목차

중첩 타입

이름 정의
type 모든 T 에 대한 공통 타입

헬퍼 타입

template < class ... T >
using common_type_t = typename common_type < T... > :: type ;
(C++14부터)

특수화

사용자는 common_type T1 T2 타입에 대해 특수화할 수 있습니다.

  • T1 T2 중 적어도 하나가 사용자 정의 타입에 의존하며,
  • std::decay T1 T2 모두에 대해 항등 변환입니다.

그러한 특수화가 type 이라는 멤버를 가질 경우, 이는 T1 T2 모두가 명시적으로 변환 가능한 cv-한정자가 없는 비참조 타입을 지칭하는 공개적이고 모호하지 않은 멤버여야 합니다. 추가적으로, std :: common_type < T1, T2 > :: type std :: common_type < T2, T1 > :: type 는 동일한 타입을 나타내야 합니다.

이러한 규칙을 위반하여 common_type 특수화를 추가하는 프로그램은 미정의 동작을 가집니다.

std::basic_common_reference 를 제외한 ( std::basic_common_reference ) (C++20부터) <type_traits> 내의 다른 템플릿에 특수화를 추가하는 프로그램의 동작은 정의되지 않음에 유의하십시오.

다음 특수화들은 표준 라이브러리에서 이미 제공됩니다:

std::common_type 특성의 특수화
(클래스 템플릿 특수화)
std::common_type 특성의 특수화
(클래스 템플릿 특수화)
pair 의 공통 타입을 결정
(클래스 템플릿 특수화)
tuple tuple-like 타입의 공통 타입을 결정
(클래스 템플릿 특수화)
반복자와 적응된 basic_const_iterator 타입의 공통 타입을 결정
(클래스 템플릿 특수화)

가능한 구현

// 기본 템플릿 (0개 타입에 사용)
template<class...>
struct common_type {};
// 단일 타입
template<class T>
struct common_type<T> : common_type<T, T> {};
namespace detail
{
    template<class...>
    using void_t = void;
    template<class T1, class T2>
    using conditional_result_t = decltype(false ? std::declval<T1>() : std::declval<T2>());
    template<class, class, class = void>
    struct decay_conditional_result {};
    template<class T1, class T2>
    struct decay_conditional_result<T1, T2, void_t<conditional_result_t<T1, T2>>>
        : std::decay<conditional_result_t<T1, T2>> {};
    template<class T1, class T2, class = void>
    struct common_type_2_impl : decay_conditional_result<const T1&, const T2&> {};
    // C++11 구현:
    // template<class, class, class = void>
    // struct common_type_2_impl {};
    template<class T1, class T2>
    struct common_type_2_impl<T1, T2, void_t<conditional_result_t<T1, T2>>>
        : decay_conditional_result<T1, T2> {};
}
// 두 개 타입
template<class T1, class T2>
struct common_type<T1, T2> 
    : std::conditional<std::is_same<T1, typename std::decay<T1>::type>::value &&
                       std::is_same<T2, typename std::decay<T2>::type>::value,
                       detail::common_type_2_impl<T1, T2>,
                       common_type<typename std::decay<T1>::type,
                                   typename std::decay<T2>::type>>::type {};
// 3개 이상 타입
namespace detail
{
    template<class AlwaysVoid, class T1, class T2, class... R>
    struct common_type_multi_impl {};
    template<class T1, class T2, class...R>
    struct common_type_multi_impl<void_t<typename common_type<T1, T2>::type>, T1, T2, R...>
        : common_type<typename common_type<T1, T2>::type, R...> {};
}
template<class T1, class T2, class... R>
struct common_type<T1, T2, R...>
    : detail::common_type_multi_impl<void, T1, T2, R...> {};

참고 사항

승격의 대상이 아닌 산술 타입에 대해, 공통 타입은 다음과 같은 (혼합 모드일 수 있는) 산술 표현식의 타입으로 볼 수 있습니다: T0 ( ) + T1 ( ) + ... + Tn ( ) .

예제

프로그램 정의 클래스에서 혼합 모드 산술 연산을 보여줍니다:

#include <iostream>
#include <type_traits>
template<class T>
struct Number { T n; };
template<class T, class U>
constexpr Number<std::common_type_t<T, U>>
    operator+(const Number<T>& lhs, const Number<U>& rhs)
{
    return {lhs.n + rhs.n};
}
void describe(const char* expr, const Number<int>& x)
{
    std::cout << expr << "  is  Number<int>{" << x.n << "}\n";
}
void describe(const char* expr, const Number<double>& x)
{
    std::cout << expr << "  is  Number<double>{" << x.n << "}\n";
}
int main()
{
    Number<int> i1 = {1}, i2 = {2};
    Number<double> d1 = {2.3}, d2 = {3.5};
    describe("i1 + i2", i1 + i2);
    describe("i1 + d2", i1 + d2);
    describe("d1 + i2", d1 + i2);
    describe("d1 + d2", d1 + d2);
}

출력:

i1 + i2  is  Number<int>{3}
i1 + d2  is  Number<double>{4.5}
d1 + i2  is  Number<double>{4.3}
d1 + d2  is  Number<double>{5.8}

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2141 C++11 조건부 연산자의 결과 타입이 decay되지 않았음 결과 타입을 decay시킴
LWG 2408 C++11 common_type 이 SFINAE-friendly하지 않았음 SFINAE-friendly하게 만듦
LWG 2460 C++11 common_type 특수화 작성이 거의 불가능했음 필요한 특수화의 수를
줄임

참고 항목

두 타입이 공통 타입을 공유함을 명시
(concept)