C++基础语法备忘录

系列文章目录



前言


一、模板

模板主要是用于避免函数的重复调用

代码如下:

#include <iostream>
#include <typeinfo>
using namespace std;
// 函数模板
// 声明模板
template<typename T>
// 模板内容:函数及变量类型,函数名
T sum(T x, T y)
{
    cout << "The input type is " << typeid(T).name() << endl;
    return x + y;
}

struct Point
{
    int x;
    int y;
};

// Specialization for Point + Point operation
// 特例话,要加<>:专门定义结构体的类型的加法计算
template<>
Point sum<Point>(Point pt1, Point pt2)
{
    cout << "The input type is " << typeid(pt1).name() << endl;
    Point pt;
    pt.x = pt1.x + pt2.x;
    pt.y = pt1.y + pt2.y;
    return pt;
}


int main()
{
    //Explicit instantiated functions
    cout << "sum = " << sum(1, 2) << endl;
    cout << "sum = " << sum(1.1, 2.2) << endl;

    Point pt1 {1, 2};
    Point pt2 {2, 3};
    Point pt = sum(pt1, pt2);
    cout << "pt = (" << pt.x << ", " << pt.y << ")" << endl;
    return 0;
}
// sum = The input type is i
// 3
// sum = The input type is d
// 3.3
// The input type is 5Point
// pt = (3, 5)

2.显示实例化

代码如下:

#include <iostream>
#include <typeinfo>
using namespace std;
// T公用数据类型
template<typename T>
T sum(T x, T y)
{
    cout << "The input type is " << typeid(T).name() << endl;
    return x +
     y;
}
// Explicitly instantiate
// 模版显式实例化
template double sum<double>(double, double);
// template double sum<>(double, double);
// template double sum(double, double);

int main()
{
    auto val = sum(4.1, 5.2);
    cout << val << endl;
    return 0;
}

2.隐式实例化

代码如下(示例):

#include <iostream>
#include <typeinfo>
using namespace std;
// T公用数据类型
template<typename T>
T sum(T x, T y)
{
    cout << "The input type is " << typeid(T).name() << endl;
    return x +
     y;
}
// Explicitly instantiate
// 模版显式实例化
template double sum<double>(double, double);
// template double sum<>(double, double);
// template double sum(double, double);

int main()
{
    auto val = sum(4.1, 5.2);
    cout << val << endl;
    return 0;
}


总结

代码参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云朵不吃雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值