C++模板元編程(Template Metaprogramming)是一種在編譯時進行計算和代碼生成的技術,它使用C++的模板機制來實現。
下面是一個簡單的C++模板元編程的示例,展示了如何在編譯時計算一個數的階乘。
#include <iostream>
template <int N>
struct Factorial {
static constexpr int value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> {
static constexpr int value = 1;
};
int main() {
constexpr int num = 5;
std::cout << "Factorial of " << num << " is: " << Factorial<num>::value << std::endl;
return 0;
}
示例中,我們定義了一個模板結構體`Factorial`,它接受一個整數模板參數`N`。`Factorial`結構體有一個靜態成員變量`value`,用于存儲計算出來的階乘值。
然后,我們使用遞歸的方式來實現階乘的計算。當`N`不為0時,`Factorial<N>::value`的值等于`N`乘以`Fa