類型特性
類型特性定義一個編譯時基于模板的結構,以查詢或修改類型的屬性。
試圖特化定義于 <type_traits> 頭文件的模板導致未定義行為,除了 std::common_type 可依照其所描述特化。
定義于<type_traits>頭文件的模板可以用不完整類型實例化,除非另外有指定,盡管通常禁止以不完整類型實例化標準庫模板。
?
類型修改
類型修改模板通過應用修改到模板參數,創建新類型定義。結果類型可以通過成員 typedef type 訪問。
?
添加 const 或/與 volatile 限定符到給定類型
std::add_cv,
std::add_const,
std::add_volatile
template< class T > | (1) | (C++11 起) |
template< class T > | (2) | (C++11 起) |
template< class T > | (3) | (C++11 起) |
提供同 T
的成員 typedef type
,除了它擁有添加的 cv 限定符(除非 T
是函數、引用或已擁有 cv 限定符)。
1) 添加 const 和 volatile
2) 添加 const
3) 添加 volatile
成員類型
名稱 | 定義 |
type | 帶 cv 限定符的類型 T |
輔助類型
template< class T > | (C++14 起) | |
template< class T > | (C++14 起) | |
template< class T > | (C++14 起) |
可能的實現
template< class T >
struct add_cv { typedef const volatile T type; };template< class T> struct add_const { typedef const T type; };template< class T> struct add_volatile { typedef volatile T type; };
調用示例
#include <iostream>
#include <type_traits>struct foo
{void m(){std::cout << "Non-cv" << std::endl;}void m() const{std::cout << "Const" << std::endl;}void m() volatile{std::cout << "Volatile" << std::endl;}void m() const volatile{std::cout << "Const-volatile" << std::endl;}
};int main()
{foo{}.m();std::cout << "std::add_const<foo>::type: ";std::add_const<foo>::type{}.m();std::cout << "std::add_volatile<foo>::type: ";std::add_volatile<foo>::type{}.m();std::cout << "std::add_cv<foo>::type: ";std::add_cv<foo>::type{}.m();return 0;
}
輸出
Non-cv
std::add_const<foo>::type: Const
std::add_volatile<foo>::type: Volatile
std::add_cv<foo>::type: Const-volatile