模板template的应用

学习的网址:

C++ 模板详解  https://www.runoob.com/w3cnote/c-templates-detail.html

C++模板template用法 https://www.jianshu.com/p/31d7e18372e2

C++中 模板Template的使用 https://www.cnblogs.com/cynchanpin/p/7127897.html

通常有两种形式:函数模板  和   类模板

函数模板

 1. 函数模板的经典例子:   

#include <iostream>

//swap函数编译不过和系统自带的有冲突,用了swap1
template<typename T> void swap1(T &a, T &b)
{

    T tmp{a};
    a = b;
    b = tmp;

}

int main(int argc, char* argv[])
{

    int a = 2;
    int b = 3;

    swap1(a, b); // 使用函数模板

    std::cout << "a=" << a << ", b=" << b << std::endl;

    double c = 1.1;
    double d = 2.2;
    swap(c, d);
    std::cout << "c=" << c << ", d=" << d << std::endl;
    return 0;

}

函数模板的声明形式为: 

//多个形参
template <class 形参名,class 形参名,......> 返回类型 函数名(参数列表)
{
    函数体
}

template <class T1,class T2,......> 返回类型 函数名(参数列表)
{
    函数体
}

//单个形参
//typename(或class)是声明数据类型參数标识符的关键字
template <typename T> 返回类型 函数名(参数列表)
{
    函数体
}

隐式实例化: 可能影响效率,

显式实例化: 在编译期间就会生成实例(增加了编译时间)

类模板

#include <iostream>
using namespace std;
template <class T>
class A
{

public:
    T value;
    template <class T2>
    void Func(T2 t) { cout << t<<endl; }  //成员函数模板
    //cout 需要加上<<endl;才能显示到终端
    //cout cout<<t;      终端没有显示
};

int main()
{
    A<int> a;
    a.value = 10;
    a.value = 5.0; //value =5
    a.Func('K');  //成员函数模板Func被实例化
    a.Func("hello");

    cout<<"hello world"<<endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值