std::remove_cv, std::remove_const, std::remove_volatile
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class T > struct remove_cv; |
(1) | (C++11 起) |
template< class T > struct remove_const; |
(2) | (C++11 起) |
template< class T > struct remove_volatile; |
(3) | (C++11 起) |
提供成員 typedef type
,其與 T
相同,但移除了其最頂層的 cv 限定符。
1) 移除最頂層的 const、最頂層的 volatile,或兩者兼有(如果存在)。
2) 移除最頂層的 const。
3) 移除最頂層的 volatile。
如果程式為此頁上描述的任何模板新增特化,則行為未定義。
目錄 |
[編輯] 成員型別
名稱 | 定義 |
型別
|
不帶 cv 限定符的型別 T |
[編輯] 輔助型別
template< class T > using remove_cv_t = typename remove_cv<T>::type; |
(C++14 起) | |
template< class T > using remove_const_t = typename remove_const<T>::type; |
(C++14 起) | |
template< class T > using remove_volatile_t = typename remove_volatile<T>::type; |
(C++14 起) | |
[編輯] 可能的實現
template<class T> struct remove_cv { typedef T type; }; template<class T> struct remove_cv<const T> { typedef T type; }; template<class T> struct remove_cv<volatile T> { typedef T type; }; template<class T> struct remove_cv<const volatile T> { typedef T type; }; template<class T> struct remove_const { typedef T type; }; template<class T> struct remove_const<const T> { typedef T type; }; template<class T> struct remove_volatile { typedef T type; }; template<class T> struct remove_volatile<volatile T> { typedef T type; }; |
[編輯] 示例
從 const volatile int* 中移除 const/volatile 不會修改型別,因為指標本身既不是 const 也不是 volatile。
執行此程式碼
#include <type_traits> template<typename U, typename V> constexpr bool same = std::is_same_v<U, V>; static_assert ( same<std::remove_cv_t<int>, int> && same<std::remove_cv_t<const int>, int> && same<std::remove_cv_t<volatile int>, int> && same<std::remove_cv_t<const volatile int>, int> && // remove_cv only works on types, not on pointers not same<std::remove_cv_t<const volatile int*>, int*> && same<std::remove_cv_t<const volatile int*>, const volatile int*> && same<std::remove_cv_t<const int* volatile>, const int*> && same<std::remove_cv_t<int* const volatile>, int*> ); int main() {}
[編輯] 參閱
(C++11) |
檢查型別是否為 const 限定 (類模板) |
(C++11) |
檢查型別是否為 volatile 限定 (類模板) |
(C++11)(C++11)(C++11) |
向給定型別新增 const 和/或 volatile 限定符 (類模板) |
(C++20) |
結合 std::remove_cv 和 std::remove_reference (類模板) |