types_is_const (타입의 const 한정 여부 확인)
이 페이지는 C++ 표준 라이브러리의 std::is_const 타입 특성에 대해 설명해요. std::is_const는 주어진 타입이 const 한정인지 여부를 컴파일 타임에 판별하는 데 사용돼요. 이 특성은 템플릿 메타프로그래밍에서 타입의 속성을 검사할 때 유용해요.
출처: cppreference
본문
std::is_const는 UnaryTypeTrait입니다. T가 const 한정 타입(즉, const 또는 const volatile)이라면 멤버 상수 value가 true와 같게 제공됩니다. 다른 모든 타입에 대해서는 value가 false입니다. 프로그램이 std::is_const 또는 std::is_const_v에 대한 특수화를 추가하면 동작은 정의되지 않습니다.
헤더 <type_traits>에 정의됨
| Defined in header <type_traits> |
|
|
template < class T > struct is_const ; |
|
(C++11부터) |
템플릿 매개변수
헬퍼 변수 템플릿
template < class T > constexpr bool is_const_v = is_const < T >:: value ; |
|
(C++17부터) |
std::integral_constant에서 상속됨
멤버 상수
value [static] |
T가 const 한정 타입이면 true, 그렇지 않으면 false (공용 정적 멤버 상수) |
멤버 함수
operator bool |
객체를 bool로 변환하고 value를 반환합니다 (공용 멤버 함수) |
operator() (C++14) |
value를 반환합니다 (공용 멤버 함수) |
멤버 타입
| 타입 |
정의 |
value_type |
bool |
type |
std :: integral_constant < bool , value > |
참고 사항
T가 참조 타입이라면 is_const < T >:: value는 항상 false입니다. 잠재적으로 참조일 수 있는 타입의 const 여부를 확인하는 올바른 방법은 참조를 제거하는 것입니다: is_const < typename remove_reference < T >:: type >.
가능한 구현
template < class T > struct is_const : std :: false_type {};
template < class T > struct is_const < const T > : std :: true_type {};
예제
#include <type_traits>
static_assert(std::is_same_v<const int*, int const*>,
"Remember, constness binds tightly inside pointers.");
static_assert(!std::is_const_v<int>);
static_assert(std::is_const_v<const int>);
static_assert(!std::is_const_v<int*>);
static_assert(std::is_const_v<int* const>,
"Because the pointer itself can't be changed but the int pointed at can.");
static_assert(!std::is_const_v<const int*>,
"Because the pointer itself can be changed but not the int pointed at.");
static_assert(!std::is_const_v<const int&>);
static_assert(std::is_const_v<std::remove_reference_t<const int&>>);
struct S
{
void foo() const {}
void bar() const {}
};
int main()
{
// A const member function is const in a different way:
static_assert(!std::is_const_v<decltype(&S::foo)>,
"Because &S::foo is a pointer.");
using S_mem_fun_ptr = void(S::*)() const;
S_mem_fun_ptr sfp = &S::foo;
sfp = &S::bar; // OK, can be re-pointed
static_assert(!std::is_const_v<decltype(sfp)>,
"Because sfp is the same pointer type and thus can be re-pointed.");
const S_mem_fun_ptr csfp = &S::foo;
// csfp = &S::bar; // Error
static_assert(std::is_const_v<decltype(csfp)>,
"Because csfp cannot be re-pointed.");
}
같이 보기
is_volatile (C++11) |
타입이 volatile 한정인지 확인합니다 (클래스 템플릿) |
as_const (C++17) |
인자에 대한 const 참조를 얻습니다 (함수 템플릿) |
is_const (C++26) |
리플렉션이 const 타입 또는 const 한정자를 가진 함수 타입을 나타내는지 확인합니다 (함수) |
is_const_type (C++26) |
리플렉션이 const 한정 타입을 나타내는지 확인합니다 (함수) |
더 알아보기 (Learn more)
cppreference