types_conjunction

types_conjunction (논리곱 메타함수)

<type_traits> 헤더에 정의된 std::conjunction은 여러 타입 특성의 논리곱(AND)을 형성하는 메타함수예요. 템플릿 인자로 받은 특성들을 순서대로 평가하면서 첫 번째 false 값을 찾아내는 방식으로 동작해요. C++17부터 사용할 수 있어요.

출처: cppreference

본문

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

Defined in header <type_traits>
template < class ... B > struct conjunction ; (since C++17)

std::conjunction은 타입 특성 B...의 논리곱을 형성해서, 특성 시퀀스에 대해 논리 AND를 수행해요.

std::conjunction<B1, ..., BN> 특수화는 공개적이고 모호하지 않은 기본 클래스를 가지는데, 그 기본 클래스는 다음과 같아요.

  • sizeof...(B) == 0이면 std::true_type이고, 그렇지 않으면
  • B1, ..., BNbool(Bi::value) == false인 첫 번째 타입 Bi이거나, 그런 타입이 없으면 BN이에요.

conjunctionoperator=를 제외한 기본 클래스의 멤버 이름은 숨겨지지 않으며 conjunction에서 모호하지 않게 사용할 수 있어요.

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

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

템플릿 매개변수

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

헬퍼 변수 템플릿

template < class ... B > constexpr bool conjunction_v = conjunction < B ... >:: value ; (since C++17)

가능한 구현

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

참고 사항

conjunction의 특수화는 반드시 std::true_type이나 std::false_type에서 상속받는 것은 아니에요. 명시적으로 bool로 변환했을 때 false인 첫 번째 B에서 상속받거나, 모두 true로 변환되면 마지막 B에서 상속받아요. 예를 들어, std::conjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value4예요.

단락 인스턴스화는 conjunction을 폴드 표현식과 구분해요. (... && Bs::value) 같은 폴드 표현식은 Bs의 모든 B를 인스턴스화하지만, std::conjunction_v<Bs...>는 값이 결정될 수 있으면 인스턴스화를 중단해요. 이는 이후의 타입이 인스턴스화 비용이 높거나 잘못된 타입으로 인스턴스화하면 하드 오류가 발생할 수 있는 경우에 특히 유용해요.

Feature-test macro Value Std Feature
__cpp_lib_logical_traits 201510L (C++17) Logical operator type traits

예제

#include <iostream>
#include <type_traits>

// func is enabled if all Ts... have the same type as T
template<typename T, typename... Ts>
std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...>>
func(T, Ts...)
{
    std::cout << "All types in pack are the same.\n";
}

// otherwise
template<typename T, typename... Ts>
std::enable_if_t<!std::conjunction_v<std::is_same<T, Ts>...>>
func(T, Ts...)
{
    std::cout << "Not all types in pack are the same.\n";
}

template<typename T, typename... Ts>
constexpr bool all_types_are_same = std::conjunction_v<std::is_same<T, Ts>...>;

static_assert(all_types_are_same<int, int, int>);
static_assert(not all_types_are_same<int, int&, int>);

int main()
{
    func(1, 2, 3);
    func(1, 2, "hello!");
}

출력:

All types in pack are the same.
Not all types in pack are the same.

같이 보기

negation (C++17) 논리 NOT 메타함수 (클래스 템플릿)
disjunction (C++17) 가변 인자 논리 OR 메타함수 (클래스 템플릿)

더 알아보기 (Learn more)

cppreference