std::is_const
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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 | - | 要检查的类型 |
辅助变量模板
<tbody> </tbody> template< class T > constexpr bool is_const_v = is_const<T>::value; |
(C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] |
如果 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。检查可能为引用的类型的常性的正确方式是移除引用: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*>,
"要记住,const 是紧密绑定到指针内部的。");
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>,
"因为可以改变指针自身而非其所指向的 int。");
static_assert(!std::is_const_v<const int*>,
"因为不能改变指针自身但可以改变其所指向的 int。");
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()
{
// const 成员函数作为 const 的方式是不同的:
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,可以改变指向
static_assert(!std::is_const_v<decltype(sfp)>,
"因为 sfp 具有相同的指针类型所以可以改变指向。");
const S_mem_fun_ptr csfp = &S::foo;
// csfp = &S::bar; // 错误
static_assert(std::is_const_v<decltype(csfp)>,
"因为 csfp 不能改变指向。");
}
参阅
(C++11) |
检查类型是否为 volatile 限定 (类模板) |
(C++17) |
获得到其实参的 const 引用 (函数模板) |