一 If结构
- 这种结构的模板参数是一个非类型参数
- 利用特化实现了true和false的不同处理
// 主模版
template <bool>
struct templateA;
// true分支
template <>
struct templateA<true>
{
};
// false分支
template <>
struct templateA<false>
{
};
C++17 特性中的if条件编译
constexpr bool aaaa = true;
if constexpr (aaaa)
qDebug()<<"aaaaa";
else
qDebug()<<"bbbbb";来进行条件编译
二 Swtich结构
// 主模版
template <int Case>
struct templateA;
template <>
struct templateA<1>
{
};
template <>
struct templateA<2>
{
};
三 for结构
- 编译期的循环
- 这里的ForTemplate<N>用到了模板递归
// 主模版
template <int N>
struct ForTemplate
{
static void F()
{
qDebug()<<"循环的执行语句"<<N;
ForTemplate<N-1>::F();
}
};
- 由于这样没有终止这个递归的条件,所以需要利用全特化终止递归
template <>
struct ForTemplate<0>
{
static void F()
{
qDebug()<<"循环的执行语句结束";
}
};
// 调用
ForTemplate<100>::F();