std::is_const_C++中文网

template< class T >
struct is_const;

(C++11 起)

T 为 const 限定类型(即 constconst volatile ),则提供等于 true 的成员常量 value 。对于任何其他类型, valuefalse

添加 is_const is_const_v (C++17 起) 的特化的程序行为未定义。

模板形参

辅助变量模板

template< class T >
inline constexpr bool is_const_v = is_const<T>::value;

(C++17 起)

继承自 std::integral_constant

成员常量

T 为 const 限定类型则为 true ,否则为 false
(公开静态成员常量)

成员函数

转换对象为 bool ,返回 value
(公开成员函数)
返回 value
(公开成员函数)

成员类型

注意

T 为引用类型则 is_const<T>::value 始终为 false 。检查可能为引用的类型的常性的正确方式是移除引用: is_const<typename remove_reference<T>::type>

可能的实现

示例

#include <iostream>
#include <type_traits>
 
int main() 
{
    std::cout << std::boolalpha;
    std::cout << std::is_const<int>::value << '\n'; // false
    std::cout << std::is_const<const int>::value  << '\n'; // true
    std::cout << std::is_const<const int*>::value  << '\n'; // false
    std::cout << std::is_const<int* const>::value  << '\n'; // true
    std::cout << std::is_const<const int&>::value  << '\n'; // false
    std::cout << std::is_const<typename std::remove_reference<const int&>::type>::value << '\n'; // true
}

输出:

false
true
false
true
false
true

参阅