C++拾遗–函数模板

<

div id=”content” contentScore=”2955″>前言

泛型的核心思想是数据与算法分离。函数模板是泛型编程的基础。

函数模板

函数模板以 template 开头,arg_list是泛型参数的列表。

1.模板的泛型参数个数确定

实例一

下面是一个加法函数模板,在实例化时,我们传入普通的数据类型。

#include
using namespace std;

template
auto add(T1 t1, T2 t2)->decltype(t1 + t2)
{
 return t1 + t2;
}
int main()
{
 cout << add(12.3, 12) << endl;
 cout << add(12, 12.3) << endl;
 cin.get();
 return 0;
}

运行

实例二

我们也可以传入函数类型。

#include
using namespace std;

template
void exec(const T &t, F f)
{
 f(t);
}
int main()
{
 exec(“calc”, system);
 cin.get();
 return 0;
}

运行 system(“calc”); 打开计算器

2.模板的泛型参数个数不确定

#include
#include
using namespace std;

//这个空参的函数用于递归终止
void show()
{
 
}
//参数个数可变,参数类型也多样
template    //typename…Args是可变类型列表
void show(T t, Args…args)
{
 cout << t << ends;
 show(args…);
}
int main()
{
 show(1, 2, 3, 4); cout << endl;
 show(‘a’, ‘b’, ‘c’, ‘d’);
 cin.get();
 return 0;
}

运行

下面利用函数模板来简单的模仿下printf()函数

#include
#include
using namespace std;

void PRINTF(const char format)
{
 cout << format;
}
template
void PRINTF(const char *format, T t, Args…args)
{
 if (!format || *format == ‘’)
  return;
 if (
format == ‘%’)    //处理格式提示符
 {
  format++;
  char c = *format;
  if (c == ‘d’ || c == ‘f’ || c == ‘c’ || c == ‘g’)  //我们暂且只处理这几种,其它的同理
  {
   cout << t;
   format++;
   PRINTF(format, args…);
  }
  else if (c == ‘%’)
  {
   cout << ‘%’;
   format++;
   PRINTF(format, t, args…);
  }
  else
  {
   cout << *format;
   format++;
   PRINTF(format, t, args…);
  }
 }
 else
 {
  cout << *format;
  PRINTF(++format, t, args…);
 }
}
int main()
{
 PRINTF(“%asdljl%5234la;jdfl;n”);
 PRINTF(“%d alsd, %fasdf..%g..%cn”, 12, 3.4, 5.897, ‘a’);
 cin.get();
 return 0;
}

运行

利用函数模板简易模拟printf()代码下载

免费下载地址在 http://linux.linuxidc.com/

用户名与密码都是www.linuxidc.com

具体下载目录在 /2015年资料/2月/19日/C拾遗–函数模板/

下载方法见 http://www.linuxidc.com/Linux/2013-07/87684.htm

——————————分割线——————————

C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm

读C++ Primer 之构造函数陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

读C++ Primer 之智能指针 http://www.linuxidc.com/Linux/2011-08/40177.htm

读C++ Primer 之句柄类 http://www.linuxidc.com/Linux/2011-08/40175.htm

将C语言梳理一下,分布在以下10个章节中:

<

ol>

  • Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  • Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  • Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  • Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  • Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  • Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  • Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  • Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  • Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  • Linux-C成长之路(十):其他高级议颼/div>