C++模板

一、函数模板基本使用

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

template <typename T>
void Swap(T& a, T& b)
{
    T tmp = a;
    a = b;
    b = tmp;
}

int main()
{
    string a = "dasdas", b = "lIDSA";
    // 以下两种写法均可
    Swap(a, b);         // 自动推导数据类型 
    Swap<string>(a, b); // 手动指定数据类型
    cout << a << ' ' << b << endl;
    
    return 0;
}

二、可以为类的成员函数创建模板,但不能是虚函数和析构函数

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

class CGirl
{
public:
    template <typename T>
    CGirl(const T& data)
    {
        cout << "data: " << data << endl;
    }
    template <typename T>
    void show(const T& data)
    {
        cout << data << endl;
    }
    // error: templates may not be 'virtual'
    /*
    template <typename T>
    virtual void vir_show(const T& data)
    {
        cout << data << endl;
    }
    */
};

int main()
{
    CGirl g("little turtle");
    g.show("show show show");
    
    return 0;
}

三、使用函数模板时,如果是自动类型推导,不会发生隐式类型转换,如果显式指定了函数模板的数据类型,可以发生隐式类型转换

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

template <typename T>
T Add(const T& a, const T& b)
{
    return a + b;
}


int main()
{
    int a = 19;
    char b = 'x';
    // 当类型不匹配时,b是不会通过隐式类型转换转换成int的
    // 需要手动指定模板类型
    // 其实也很好理解,因为我们传入模板函数的参数有两种类型
    // 编译器不知道该将两种类型统一成哪一种类型
    // 尽管char可以转换成int,但是编译器没有这样做,毕竟是费力不讨好的事情
    int c = Add<int>(a, b);
    cout << c << endl;
    
    return 0;
}

四、函数模板支持多个通用数据类型的参数

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

template <typename T1, typename T2>
void show(const T1& a, const T2& b)
{
    cout << a << ' ' << b << endl;
}

int main()
{
    int a = 85;
    string str = "lalallala";
    show(a, str);
    show(str, a);
    
    return 0;
}

五、函数模板支持重载,可以有非通用数据类型的参数

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

// show()有3个重载函数
template <typename T>
void show(const T& a)
{
    cout << a << endl;
}

template <typename T1, typename T2>
void show(const T1& a, const T2& b)
{
    cout << a << ' ' << b << endl;
}

// 这个重载函数中的第3个参数就是非通用数据类型
template <typename T1, typename T2>
void show(const T1& a, const T2& b, int c)
{
    cout << a << ' ' << b << ' ' << c << endl;
}

int main()
{
    int a = 85;
    string str = "lalallala";
    show(a);
    show(str, a);
    show(str, str, a);
    
    return 0;
}

总结

  • 可以为类的成员函数创建模板,但不能是虚函数和析构函数
  • 使用函数模板时,如果是自动类型推导,不会发生隐式类型转换,如果显式指定了函数模板的数据类型,可以发生隐式类型转换
  • 函数模板支持多个通用数据类型的参数
  • 函数模板支持重载,可以有非通用数据类型的参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值