C++中的Template常见用法

目录

摘要

函数模板

基本用法

重载与特化

类模板

基本用法

模板特化(Specialization)与偏特化(Partial Specialization)

别名模板(Alias Templates)

基本用法

变量模板(Variable Templates)

基本用法

模板模板参数(Template Template Parameters)

基本用法

总结


摘要

C++中的模板(template)是一种非常强大的工具,用于泛型编程和代码复用。模板可以分为函数模板、类模板、别名模板、变量模板、模板模板参数等。这些模板能够处理任意类型的数据,提高代码的灵活性和可重用性。

函数模板

函数模板允许函数对任意类型的数据进行操作。

基本用法

#include <iostream>

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << "Max of 3 and 7: " << max(3, 7) << std::endl;
    std::cout << "Max of 3.5 and 2.1: " << max(3.5, 2.1) << std::endl;
    std::cout << "Max of 'a' and 'z': " << max('a', 'z') << std::endl;
    return 0;
}

重载与特化

函数模板可以与普通函数重载,并且可以进行模板特化。

#include <iostream>

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

// 特化版本
template <>
const char* max(const char* a, const char* b) {
    return (std::strcmp(a, b) > 0) ? a : b;
}

// 重载版本
int max(int a, int b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << "Max of 3 and 7: " << max(3, 7) << std::endl;
    std::cout << "Max of \"hello\" and \"world\": " << max("hello", "world") << std::endl;
    return 0;
}


// Out
Max of 3 and 7: 7
Max of "hello" and "world": world

类模板

类模板允许类处理任意类型的数据。

基本用法

#include <iostream>

template <typename T>
class Pair {
private:
    T first, second;
public:
    Pair(T a, T b) : first(a), second(b) {}
    T getFirst() const { return first; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉夢志昂丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值