type traits library (tsz. type traits libraries)
<type_traits>
fejléccel), amely típusokról ad információt fordítási időben, és lehetővé teszi, hogy sablonokat típusfüggően módosítsunk. Ez a könyvtár a template metaprogramming egyik alapköve.
#include <type_traits>
int
, float
, pointer
, class
, stb.const
, referencia, pointer stb.enable_if
): Csak bizonyos típusokra engedjük egy sablon instanciálását.constexpr if
vagy std::conditional
alapján.
std::is_integral<T>::value
std::is_integral<int>::value // true
std::is_integral<double>::value // false
std::is_pointer<T>::value
std::is_pointer<int*>::value // true
std::is_pointer<int>::value // false
std::is_same<T1, T2>::value
std::is_same<int, int>::value // true
std::is_same<int, const int>::value // false
std::remove_const<T>::type
using T = const int;
using U = std::remove_const<T>::type; // U == int
std::remove_reference<T>::type
int& ref = x;
std::remove_reference<decltype(ref)>::type // int
std::decay<T>::type
Olyan típusra alakít, mint amit egy függvényparaméter automatikusan felvenne:
std::decay<int&>::type // int
std::decay<int>::type // int*
std::conditional
template<bool B>
using int_or_double = typename std::conditional<B, int, double>::type;
int_or_double<true> x = 5; // int
int_or_double<false> y = 3.14; // double
std::enable_if
template<typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
dupla(T x) {
return x * 2;
}
Alternatíva C++20-tól: requires
és koncepciók (concepts
).
type_traits
típusokNév | Leírás |
---|---|
std::is_void<T>
|
T void típus-e
|
std::is_array<T>
|
T tömb-e
|
std::is_pointer<T>
|
T* típus-e
|
std::is_reference<T>
|
referencia-e |
std::is_const<T>
|
const -e
|
std::is_class<T>
|
osztály-e |
std::is_enum<T>
|
felsorolt típus-e |
std::is_fundamental<T>
|
alapvető típus-e (int, float, stb.) |
std::is_arithmetic<T>
|
int , float , stb.
|
std::remove_pointer<T>
|
pointer eltávolítása |
std::add_const<T>
|
const T típus létrehozása
|
Fogalom | Leírás |
---|---|
Type traits könyvtár | Típusvizsgálat és típusmódosítás template-en belül |
Előnye | Fordítási időben működik, hatékony |
Használat | std::is_X , std::remove_X , std::enable_if , std::conditional
|
Modern alternatíva | C++20-tól: concepts , requires , std::is_same_v stb.
|