types_is_signed

types_is_signed (부호 있는 타입 판별)

std::is_signed는 주어진 타입 T가 부호 있는 산술 타입인지 확인하는 타입 특성(type trait)이에요. 이 특성을 사용하면 컴파일 타임에 타입의 부호 여부를 알 수 있어서, 템플릿 메타프로그래밍이나 조건부 컴파일에서 유용하게 활용할 수 있답니다. std::is_signed_v 변수 템플릿을 통해 더 간결하게 값에 접근할 수도 있어요.

출처: cppreference

본문

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

정의
template < class T > struct is_signed; (C++11 이후)

std::is_signedUnaryTypeTrait예요. T가 부호 있는 산술 타입인지 검사하죠.

  • std::is_arithmetic<T>::valuetrue라면, 멤버 상수 valueT(-1) < T(0)의 결과와 같아요.
  • 그렇지 않다면, 멤버 상수 valuefalse예요.

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

템플릿 매개변수

T - 검사할 타입

헬퍼 변수 템플릿

template < class T > constexpr bool is_signed_v = is_signed<T>::value; (C++17 이후)

std::integral_constant에서 상속받은 멤버

멤버 상수

value [static] T가 부호 있는 산술 타입이면 true, 아니면 false (공용 정적 멤버 상수)

멤버 함수

operator bool 객체를 bool로 변환하고 value를 반환해요 (공용 멤버 함수)
operator() (C++14) value를 반환해요 (공용 멤버 함수)

멤버 타입

타입 정의
value_type bool
type std::integral_constant<bool, value>

가능한 구현

namespace detail {
    template <typename T, bool = std::is_arithmetic<T>::value>
    struct is_signed : std::integral_constant<bool, T(-1) < T(0)> {};

    template <typename T>
    struct is_signed<T, false> : std::false_type {};
}

template <typename T>
struct is_signed : detail::is_signed<T>::type {};

예제

#include <iostream>
#include <type_traits>

class A {};
static_assert(std::is_signed_v<A> == false);

class B { int i; };
static_assert(std::is_signed_v<B> == false);

enum C : int {};
static_assert(std::is_signed_v<C> == false);

enum class D : int {};
static_assert(std::is_signed_v<D> == false);

static_assert
(
    std::is_signed<signed int>::value == true and // C++11
    std::is_signed<signed int>() == true and      // C++11
    std::is_signed<signed int>{} == true and      // C++11
    std::is_signed_v<signed int> == true and      // C++17
    std::is_signed_v<unsigned int> == false and
    std::is_signed_v<float> == true and
    std::is_signed_v<bool> == false and
    std::is_signed_v<signed char> == true and
    std::is_signed_v<unsigned char> == false
);

int main()
{
    // signedness of char is implementation-defined:
    std::cout << std::boolalpha << std::is_signed_v<char> << '\n';
}

가능한 출력:

true

결함 보고서

이전에 발표된 C++ 표준에 소급 적용된 동작 변경 결함 보고서는 다음과 같아요.

DR 적용 대상 발표된 동작 올바른 동작
LWG 2197 C++11 T가 산술 타입이 아니어도 valuetrue일 수 있었음 이 경우에는 false만 가능

더 알아보기

is_unsigned (C++11) 타입이 부호 없는 산술 타입인지 검사해요 (클래스 템플릿)
is_signed [static] 부호 있는 타입을 식별해요 (std::numeric_limits<T>의 공용 정적 멤버 상수)
is_arithmetic (C++11) 타입이 산술 타입인지 검사해요 (클래스 템플릿)
make_signed (C++11) 주어진 정수 타입에 대응하는 부호 있는 타입을 얻어요 (클래스 템플릿)
make_unsigned (C++11) 주어진 정수 타입에 대응하는 부호 없는 타입을 얻어요 (클래스 템플릿)
is_signed_type (C++26) 리플렉션이 부호 있는 산술 타입을 나타내는지 검사해요 (함수)

더 알아보기 (Learn more)

cppreference