名稱空間
變體
操作

std::remove_cv, std::remove_const, std::remove_volatile

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型別屬性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
remove_cvremove_constremove_volatile
(C++11)(C++11)(C++11)
(C++11)(C++11)(C++11)
型別轉換
(C++11)(C++23 中已棄用)
(C++11)(C++23 中已棄用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
定義於標頭檔案 <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 限定
(類模板) [編輯]
檢查型別是否為 volatile 限定
(類模板) [編輯]
(C++11)(C++11)(C++11)
向給定型別新增 const 和/或 volatile 限定符
(類模板) [編輯]
結合 std::remove_cvstd::remove_reference
(類模板) [編輯]