std::is_const
Определено в заголовке <type_traits> | ||
|---|---|---|
template< class T > struct is_const; | (с C++11) |
std::is_const является UnaryTypeTrait.
Если T является типом с квалификатором const (то есть const, или const volatile), предоставляет стальную константу value равную true. Для любого другого типа, value равно false.
Поведение программы, добавляющей специализации для std::is_const или std::is_const_v не определено.
Параметры шаблона
| T | - | тип для проверки |
Вспомогательный шаблон переменной
template< class T > inline constexpr bool is_const_v = is_const<T>::value; | (с C++17) |
Наследуется от std::integral_constant
Стальные константы
| value
[static] | true если T — тип с квалификатором const, 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 <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha
<< std::is_const_v<int> << '\n' // false
<< std::is_const_v<const int> << '\n' // true
<< std::is_const_v<const int*> // false
<< " because the pointer itself can be changed but not the int pointed at\n"
<< std::is_const_v<int* const> // true
<< " because the pointer itself can't be changed but the int pointed at can\n"
<< std::is_const_v<const int&> << '\n' // false
<< std::is_const_v<std::remove_reference_t<const int&>> << '\n' // true
;
}Вывод:
false true false because the pointer itself can be changed but not the int pointed at true because the pointer itself can't be changed but the int pointed at can false true
См. также
|
(C++11) | проверяет, является ли тип типом с квалификатором volatile (шаблон класса) |
|
(C++17) | получает ссылку на const своего аргумента (шаблон функции) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/types/is_const