C++
Type list
Type list ve derleme zamanı liste öğrenirsin.
Type list
Type list, derleme zamanında türleri saklayan bir veri yapısıdır. Değişken sayıda tür parametresi alan şablonla yazılır: template <typename... Ts> struct Typelist {};. Burada Ts bir tür paketidir (parameter pack).
Uzunluk, özyinelemeli bir yardımcı ile derleme zamanında hesaplanır. Boş liste uzunluğu 0, boş olmayan listenin uzunluğu 1 + Length<tail>::value. Böylece Typelist<int, double, char> için uzunluk 3 bulunur.
Length yardımcısı
Length, bir Typelist'in kaç tür içerdiğini döndürür. Genel uzmanlaşma listenin başını çıkarıp kalanı için Length'i çağırır: template <typename Head, typename... Tail> struct Length<Typelist<Head, Tail...>> { static const int value = 1 + Length<Typelist<Tail...>>::value; };.
Boş liste için template <> struct Length<Typelist<>> { static const int value = 0; };. Bu, recursive Factorial ile aynı yapıdadır; tek fark tür listesi üzerinde çalışır.
Uygulama Typelist ve Length yaz
template <typename... Ts> struct Typelist {}; tanımla. Genel Length uzmanlaşmasını 1 + Length<Typelist<Tail...>>::value ile yaz. Boş uzmanlaşmayı value = 0 ile ekle. main içinde std::cout << Length<Typelist<int, double, char>>::value; yaz.
Örnek çözümü göster
#include <iostream>
template <typename... Ts>
struct Typelist {};
template <typename List>
struct Length;
template <typename Head, typename... Tail>
struct Length<Typelist<Head, Tail...>> {
static const int value = 1 + Length<Typelist<Tail...>>::value;
};
template <>
struct Length<Typelist<>> {
static const int value = 0;
};
int main() {
std::cout << Length<Typelist<int, double, char>>::value;
return 0;
}
Kendini test et
-
Parçayı rolüne eşle
- typename... Ts
- Tür paketi
- struct Typelist
- Liste yapısı
- Length<Typelist<...>>
- Derleme zamanı uzunluk
- Typelist<int, char>
- İki tür
-
Boş liste uzunluğu
template <> struct Length<Typelist<>> { static const int value = ____; };
Cevabı göster
template <> struct Length<Typelist<>> { static const int value = 0; };
-
Typelist<int, double, char> uzunluğu?
template <typename... Ts> struct Typelist {};
template <typename Head, typename... Tail> struct Length<Typelist<Head, Tail...>> { static const int value = 1 + Length<Typelist<Tail...>>::value; };
Cevabı göster
3 — int, double ve char üç türdür; uzunluk 3.
Sıradaki ders: constexpr fonksiyon