標準型別特徵
Version >= C++ 11
type_traits
頭包含一組模板類和幫助程式,用於在編譯時轉換和檢查型別的屬性。
這些特徵通常用於模板中以檢查使用者錯誤,支援通用程式設計並允許優化。
大多數型別特徵用於檢查型別是否符合某些標準。它們具有以下形式:
template <class T> struct is_foo;
如果模板類使用滿足某些標準 foo
的型別進行例項化,則 is_foo<T>
繼承自 std::integral_constant<bool,true>
(aka std::true_type
),否則它繼承自 std::integral_constant<bool,false>
(aka std::false_type
)。這給了特徵以下成員:
常量
static constexpr bool value
true
如果 T
符合標準 foo
,false
否則
功能
operator bool
返回 value
Version => C++ 14
bool operator()
返回 value
型別
名稱 | 定義 |
---|---|
value_type |
bool |
type |
std::integral_constant<bool,value> |
然後可以將該性狀用於諸如 static_assert
或 std::enable_if
的構建體中 。std::is_pointer
的一個例子:
template <typename T>
void i_require_a_pointer (T t) {
static_assert(std::is_pointer<T>::value, "T must be a pointer type");
}
//Overload for when T is not a pointer type
template <typename T>
typename std::enable_if<!std::is_pointer<T>::value>::type
does_something_special_with_pointer (T t) {
//Do something boring
}
//Overload for when T is a pointer type
template <typename T>
typename std::enable_if<std::is_pointer<T>::value>::type
does_something_special_with_pointer (T t) {
//Do something special
}
還有各種改變型別的特徵,例如 std::add_pointer
和 std::underlying_type
。這些特徵通常暴露單個 type
成員型別,其中包含轉換型別。例如,std::add_pointer<int>::type
是 int*
。