C++自学篇 泛型编程(模板与具体化)

前言

C++的泛型编程是一种基于模板的编程技术,它允许在编写代码时使用未知的数据类型。泛型编程的目标是实现可重用、灵活和高效的代码。在C++中,泛型编程主要通过模板来实现。模板是一种用来生成代码的蓝图,它可以根据不同的数据类型生成特定的代码。
1.C++提供了两种模板:函数模板类模板。除了C++提供的函数模板和类模板,还有介于这两者之间的类成员函数模板
2.模板具体化(Template Specialization)是一种特殊情况,它允许为特定的模板参数提供特定的实现。当模板代码无法满足特定类型或特定条件的需求时,可以使用模板具体化来提供针对这些特定情况的定制实现。模板具体化分为两种类型:完全具体化(Full Specialization)和偏特化(Partial Specialization)。完全具体化:完全具体化是对模板的每个模板参数都提供了特定的实现。偏特化:偏特化是对模板的部分模板参数提供特定的实现。

函数模板

代码如下:

#include <iostream>

template <typename T>
T tempConver(T val);

int main(int argc, char *argv[])
{
   
    const int intInput[] = {
   12, 13};
    const float floatInput[] = {
   12.0, 12.4, 12.5, 13.0};

    for (auto val : intInput) {
   
        auto temp = tempConver(val);
        std::cout << "[int]" << val << " -> " << temp << ": " << typeid(temp).name() << std::endl;
    }
    std::cout << std::endl;

    for (auto val : floatInput) {
   
        auto temp = tempConver(val);
        std::cout << "[float]" << val << " -> " << temp << ": " << typeid(temp).name() << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

template <typename T>
T tempConver(T val)
{
   
    auto tempF = ((val * (9 / 5)) + 32.00);
    T ret = static_cast<T>(tempF);
    return ret;
}

运行结果如下:

[int]12 -> 44: i
[int]13 -> 45: i

[float]12 -> 44: f
[float]12.4 -> 44.4: f
[float]12.5 -> 44.5: f
[float]13 -> 45: f

类模板

代码如下:

#include <iostream>
#include <memory>

template <typename T>
class UnitConver {
   
public:
    T tempConve
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值