types_disjunction

types_disjunction (논리합 타입 특성)

이 페이지는 C++17부터 사용할 수 있는 std::disjunction 타입 특성에 대해 설명해요. std::disjunction은 여러 타입 특성들의 논리합(OR)을 계산하는 메타함수로, 컴파일 타임에 조건 판별을 수행할 때 유용해요. 특히 단락 평가(short-circuit) 방식으로 동작해서 불필요한 인스턴스화를 막아줘요.

출처: cppreference

본문

정의

<type_traits> 헤더에 정의되어 있어요.

<type_traits> 헤더에 정의됨
template < class ... B > struct disjunction ; (C++17부터)

std::disjunction은 타입 특성 B...의 논리합을 구성해요. 즉, 특성들의 시퀀스에 대해 논리 OR를 수행하는 효과가 있어요.

std::disjunction<B1, ..., BN> 특수화는 다음과 같은 public이고 모호하지 않은 기본 클래스를 가져요:

  • sizeof...(B) == 0이면 std::false_type, 그렇지 않으면
  • B1, ..., BN 중에서 bool(Bi::value) == true인 첫 번째 타입 Bi, 또는 그런 타입이 없으면 BN.

기본 클래스의 멤버 이름 중 disjunctionoperator=를 제외한 나머지는 숨겨지지 않으며 disjunction에서 모호함 없이 사용할 수 있어요.

std::disjunction은 단락 평가를 해요. 만약 bool(Bi::value) != false인 템플릿 타입 인자 Bi가 있다면, disjunction<B1, ..., BN>::value를 인스턴스화할 때 j > iBj::value의 인스턴스화는 필요하지 않아요.

프로그램에서 std::disjunction 또는 std::disjunction_v에 대한 특수화를 추가하면 동작이 정의되지 않아요.

템플릿 매개변수

B... - Bi::value가 인스턴스화되는 모든 템플릿 인자 Bi는 기본 클래스로 사용할 수 있어야 하고, bool로 변환 가능한 멤버 value를 정의해야 해요

헬퍼 변수 템플릿

template < class ... B > constexpr bool disjunction_v = disjunction < B ... >:: value ; (C++17부터)

가능한 구현

template<class...> struct disjunction : std::false_type {};
template<class B1> struct disjunction<B1> : B1 {};
template<class B1, class... Bn>
struct disjunction<B1, Bn...> : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> {};

참고 사항

std::disjunction의 특수화는 반드시 std::true_type 또는 std::false_type 중 하나를 상속하지는 않아요. 단순히 ::valuebool로 명시적 변환했을 때 true가 되는 첫 번째 B를 상속하거나, 모두 false로 변환될 때는 마지막 B를 상속해요. 예를 들어, std::disjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value2예요.

단락 인스턴스화는 disjunction을 폴드 표현식과 구별해줘요. (... || Bs::value) 같은 폴드 표현식은 Bs의 모든 B를 인스턴스화하지만, std::disjunction_v<Bs...>는 값이 결정되면 인스턴스화를 멈춰요. 이는 나중에 오는 타입이 인스턴스화 비용이 크거나, 잘못된 타입으로 인스턴스화할 때 하드 오류를 일으킬 수 있는 경우 특히 유용해요.

기능 테스트 매크로

매크로 표준 기능
__cpp_lib_logical_traits 201510L (C++17) 논리 연산자 타입 특성

예제

#include <cstdint>
#include <string>
#include <type_traits>

// values_equal<a, b, T>::value is true if and only if a == b.
template<auto V1, decltype(V1) V2, typename T>
struct values_equal : std::bool_constant<V1 == V2>
{
    using type = T;
};

// default_type<T>::value is always true
template<typename T>
struct default_type : std::true_type
{
    using type = T;
};

// Now we can use disjunction like a switch statement:
template<int I>
using int_of_size = typename std::disjunction< //
    values_equal<I, 1, std::int8_t>,           //
    values_equal<I, 2, std::int16_t>,          //
    values_equal<I, 4, std::int32_t>,          //
    values_equal<I, 8, std::int64_t>,          //
    default_type<void>                         // must be last!
    >::type;

static_assert(sizeof(int_of_size<1>) == 1);
static_assert(sizeof(int_of_size<2>) == 2);
static_assert(sizeof(int_of_size<4>) == 4);
static_assert(sizeof(int_of_size<8>) == 8);
static_assert(std::is_same_v<int_of_size<13>, void>);

// checking if Foo is constructible from double will cause a hard error
struct Foo
{
    template<class T>
    struct sfinae_unfriendly_check { static_assert(!std::is_same_v<T, double>); };

    template<class T>
    Foo(T, sfinae_unfriendly_check<T> = {});
};

template<class... Ts>
struct first_constructible
{
    template<class T, class...Args>
    struct is_constructible_x : std::is_constructible<T, Args...>
    {
        using type = T;
    };

    struct fallback
    {
        static constexpr bool value = true;
        using type = void; // type to return if nothing is found
    };

    template<class... Args>
    using with = typename std::disjunction<is_constructible_x<Ts, Args...>...,
                                           fallback>::type;
};

// OK, is_constructible<Foo, double> not instantiated
static_assert(std::is_same_v<first_constructible<std::string, int, Foo>::with<double>,
                             int>);

static_assert(std::is_same_v<first_constructible<std::string, int>::with<>, std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<const char*>,
                             std::string>);
static_assert(std::is_same_v<first_constructible<std::string, int>::with<void*>, void>);

int main() {}

같이 보기

negation (C++17) 논리 NOT 메타함수 (클래스 템플릿) [edit]
conjunction (C++17) 가변 인자 논리 AND 메타함수 (클래스 템플릿) [edit]

더 알아보기 (Learn more)

cppreference