類型特性
類型特性定義一個編譯時基于模板的結構,以查詢或修改類型的屬性。
試圖特化定義于 <type_traits> 頭文件的模板導致未定義行為,除了 std::common_type 可依照其所描述特化。
定義于<type_traits>頭文件的模板可以用不完整類型實例化,除非另外有指定,盡管通常禁止以不完整類型實例化標準庫模板。
類型修改
類型修改模板通過應用修改到模板參數,創建新類型定義。結果類型可以通過成員 typedef?type
?訪問。
從給定類型移除引用
template< class T > | (C++11 起) |
若類型 T
為引用類型,則提供成員 typedef type
,其為 T
所引用的類型。否則 type
為 T
。
成員類型
名稱 | 定義 |
type | T 所引用的類型,或若 T 不是引用則為 T |
輔助類型
template< class T > | (C++14 起) |
可能的實現
template< class T > struct remove_reference {typedef T type;};
template< class T > struct remove_reference<T&> {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};
調用示例
#include <iostream>
#include <type_traits>int main()
{std::cout << std::boolalpha;std::cout << "std::is_same<int, int>(): "<< std::is_same<int, int>() << std::endl;std::cout << "std::is_same<int, int &>(): "<< std::is_same<int, int &>() << std::endl;std::cout << "std::is_same<int, int && >(): "<< std::is_same < int, int && > () << std::endl;std::cout << "std::is_same<int, std::remove_reference<int>::type>(): "<< std::is_same<int, std::remove_reference<int>::type>() << std::endl;std::cout << "std::is_same<int, std::remove_reference<int &>::type>()>(): "<< std::is_same<int, std::remove_reference<int &>::type>() << std::endl;std::cout << "std::is_same<int, std::remove_reference < int && >::type>(): "<< std::is_same < int, std::remove_reference < int && >::type > () << std::endl;return 0;
}
輸出
std::is_same<int, int>(): true
std::is_same<int, int &>(): false
std::is_same<int, int && >(): false
std::is_same<int, std::remove_reference<int>::type>(): true
std::is_same<int, std::remove_reference<int &>::type>()>(): true
std::is_same<int, std::remove_reference < int && >::type>(): true