C++模板基本语法

#include <iostream>

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

int main()
{
   using namespace std;

   int a = 1;
   int b = 2;
   myswap(a, b);
   cout << "a " << a << endl;
   cout << "b " << b << endl;

   float c = 4;
   float d = 5;
   myswap<float>(c, d);
   cout << "c " << c << endl;
   cout << "d " << d << endl;

   return 0;
}
$ ./a.out         
a 2
b 1
c 5
d 4

函数模板有两种方式:自动类型推导、显示类型指定
模板的目的:提高复用性、将类型参数化

posted @   thomas_blog  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-07-13 vue Promise all
2021-07-13 vue Promise链式调用
2021-07-13 vue Promise异步操作
2021-07-13 vue 路径alias起别名
点击右上角即可分享
微信分享提示