std::is_const
來自 cppreference.com
定義於標頭檔案 <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 > constexpr bool is_const_v = is_const<T>::value; |
(C++17 起) | |
繼承自 std::integral_constant
成員常量
value [靜態] |
如果 T 是 const 限定型別,則為 true,否則為 false(public static 成員常量) |
成員函式
operator bool |
將物件轉換為 bool,返回 value (公開成員函式) |
operator() (C++14) |
返回 value (公開成員函式) |
成員型別
型別 | 定義 |
value_type
|
bool |
型別
|
std::integral_constant<bool, value> |
[編輯] 注意
如果 T 是引用型別,則 is_const<T>::value 始終為 false。檢查潛在引用型別的 constness 的正確方法是移除引用: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."); }
[編輯] 另見
(C++11) |
檢查型別是否為 volatile 限定 (類模板) |
(C++17) |
獲取其引數的 const 引用 (函式模板) |