C++模板函数复习

#include <iostream>
#include <typeinfo>
using namespace std;


template <class T>
T add(T one, T two)
{
    cout << "类型:" << typeid(T).name() << endl;
    return one + two; // 函数模板只有在调用时才编译,有的编译器在初次编译时就会编译
}

template <class T> //模板函数重载
T add(T one, T two, T three)
{
    return one+two+three;
}

template<> //函数模板具体化
int add(int one, int two)
{
    cout << "add模板函数具体化" << endl;
    return one+two;
}

int add(int one, int two)
{
    cout << "自定义int" << endl;
    return one + two;
}


template <class T, class F> //函数模板不仅可以接受数据类型,还可以接受操作类型
void show(T t, F f)
{
    f(t);
}
void show_(int temp)
{
    cout << temp << endl;
}


template<class T1, class T2>
auto temp1(T1 t1, T2 t2)->decltype(t1+t2) //自动类型推理
{
    return t1 + t2;
}


template<class T>
void temp2(T t)
{
    decltype(t) d; //创建一个与T类型相同的变量
}


int main()
{
    //cout << add(1.2, 1.2) << endl;
    //cout << add(1, 2) << endl; //如果有自定义函数 int add(int, int),则会优先使用自定义的,不然会使用函数模板

    //cout << add<int>(1,2) << endl; //如果函数模板显示实例化,则无论有没有自定义函数add,都会使用函数模板

    //show(1, show_);
    //show(1, [](int i){cout << i << " lambda" << endl;}); //可以把lambda表达式作为操作类型传给函数模板


    //int a = 10;
    //decltype(a) b = 3; //decltype的功能是拷贝数据类型


    //cout << temp(1.2, 1) << endl;
    //cout << temp(1, 1.2) << endl;


    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值