- 计算阶乘
计算阶乘的示例,使用了模板递归和模板特化:
template <unsigned int N>
struct Factorial {
static const unsigned int value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> {
static const unsigned int value = 1;
};
// 使用
int main() {
unsigned int x = Factorial<5>::value; // x will be 120
return 0;
}
- 编译时斐波那契数列
计算斐波那契数列的例子:
template <unsigned int N>
struct Fibonacci {
static const unsigned int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};
template <>
struct Fibonacci<0> {
static const unsigned int value = 0;
};
template <>
struct Fibonacci<1> {
static const unsigned int value = 1;
};
// 使用
int main() {
unsigned int x = Fibonacci<10>::value; // x will be 55
return 0;
}
- 编译时计算数组长度
计算数组长度的例子:
template<unsigned int N>
struct ArraySize {
static const unsigned int value = N;
};
#define ARRAY_SIZE(arr) (ArraySize<sizeof(arr) / sizeof(arr[0])>::value)
// 使用
int main() {
int arr[] = {1, 2, 3, 4, 5};
unsigned int size = ARRAY_SIZE(arr); // size will be 5
return 0;
}
- 类型萃取(Type Traits)
类型萃取可以让我们获取关于类型的信息。例如,我们可以创建一个模板,来确定一个类型是否为const:
template<typename T>
struct IsConst {
static const bool value = false;
};
template<typename T>
struct IsConst<const T> {
static const bool value = true;
};
// 使用
int main() {
bool b1 = IsConst<int>::value; // b1 will be false
bool b2 = IsConst<const int>::value; // b2 will be true
return 0;
}
- 编译时If
我们甚至可以在编译时实现if语句。例如,以下模板可以在编译时选择一个类型:
template<bool Condition, typename TrueType, typename FalseType>
struct CompileTimeIf;
template<typename TrueType, typename FalseType>
struct CompileTimeIf<true, TrueType, FalseType> {
using type = TrueType;
};
template<typename TrueType, typename FalseType>
struct CompileTimeIf<false, TrueType, FalseType> {
using type = FalseType;
};
// 使用
int main() {
using T = CompileTimeIf<true, int, float>::type; // T will be int
return 0;
}