Recursive template
- C++ kursu
- Uzman
- Ders 2/47
- 5 dk
Recursive template ile derleme zamanı döngü öğrenirsin.
Recursive template
Recursive template, bir şablonun kendine başvurduğu derleme zamanı döngüsüdür. Faktöriyel böyle yazılır: genel durum Factorial<N>::value = N * Factorial<N-1>::value, temel durum Factorial<0>::value = 1 ile bir uzmanlaşma (specialization) olarak verilir.
Örnek: template <int N> struct Factorial { static const int value = N * Factorial<N-1>::value; }; ve template <> struct Factorial<0> { static const int value = 1; };. Derleyici Factorial<3> için 3 * 2 * 1 * 1 zincirini derleme zamanında açar.
Uzmanlaşma ile durma
Recursion'un durması için bir uzmanlaşma (specialization) gerekir. template <> struct Factorial<0> boş parametre listesiyle tam uzmanlaşmadır. Derleyici Factorial<0>'a ulaşınca genel şablona başvurmadan value = 1 alır.
Böylece Factorial<3>::value için zincir 3 * Factorial<2> → 2 * Factorial<1> → 1 * Factorial<0> → 1 biçiminde sonlanır. Sonuç 6 olur ve çalışma zamanında sabit olarak kullanılır.
Uygulama Recursive Factorial yaz
Genel template <int N> struct Factorial yaz; gövdesi static const int value = N * Factorial<N-1>::value;. Sonra template <> struct Factorial<0> uzmanlaşmasını value = 1 ile ekle. main içinde std::cout << Factorial<5>::value; yaz.
Başlangıç kodu
#include <iostream>
// Factorial şablonunu buraya tanımla
int main() {
// Sonucu yazdır
return 0;
}Örnek çözüm
#include <iostream>
template <int N>
struct Factorial {
static const int value = N * Factorial<N-1>::value;
};
template <>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << Factorial<5>::value;
return 0;
}Beklenen çıktı
120
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Temel durumu tamamla
template <> struct Factorial<0> { static const int value = ____; };
template <> struct Factorial<0> { static const int value = 1; };
Açıklama: value = 1 yazılır; 0 faktöriyel 1'dir.
2 Factorial<3>::value kaçtır?
template <int N> struct Factorial { static const int value = N * Factorial<N-1>::value; };- 3
- 9
- 6 Doğru cevap
- 0
Açıklama: 3! = 3 * 2 * 1 = 6.
3 Çağrıyı sonucuna eşle
| Kavram | Anlamı |
|---|---|
Factorial<1>::value |
1 döner |
Factorial<3>::value |
6 döner |
Factorial<4>::value |
24 döner |
Factorial<5>::value |
120 döner |