一个例子
一个元函数往往通过类模板实现的,例如下面的struct Factorial
#include <iostream>
template <int N>
struct Factorial
{
static constexpr long long value{ N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
static constexpr long long value{ 1 };
};
int main()
{
std::cout << Factorial<0>::value << "\n";
std::cout << Factorial<1>::value << "\n";
std::cout << Factorial<3>::value << "\n";
std::cout << Factorial<5>::value << "\n";
}
在上面这个例子中,我们定义一个Factorial的全特化(full template specialization)指定base case,Factorial<0>::value
将会返回1,
而像Factorial<3>::value
会调用 3 * Factorial<2>::value
,一直执行下去,直到遇到Factorial<0>::value
。这个过程都是在编译器完成的