模板元编程例子

  1. 计算阶乘

计算阶乘的示例,使用了模板递归和模板特化:

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;
}

  1. 编译时斐波那契数列

计算斐波那契数列的例子:

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;
}

  1. 编译时计算数组长度

计算数组长度的例子:

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;
}

  1. 类型萃取(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;
}

  1. 编译时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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值