|
本帖发表于 2016-10-17 16:21:59...阅读 159 人...加油,亲爱的楼主:[db:作者]
C++的模板(template)是泛型编程(generic programming)的基础;
面向对象编程 是 运行(run time)时 知道类型(type); 泛型编程 是编译(compilation) 知道类型;
函数模板(function template)包含模板参数列表(template parameter list);
每个参数类型之前必须包含关键字typename或class, 尽量使用typename, 表达意思更加明确;
非类型模板参数(Nontype Template Parameters)只能是 整数类型, 指针, 引用;
整型必须是常量表达式(constant expression), 指针和引用必须指向静态类型;
模板函数需要保证函数的类型独立(type independence)和可移植性(portability); 尽量使用STL库函数;
代码:
/*
* cppprimer.cpp
*
* Created on: 2013.11.21
* Author: Caroline
*/
/*eclipse cdt, gcc 4.8.1*/
#include [i]
#include
#include //less
#include //strcmp
template
int compare (const T &v1, const T &v2)
{
if (std::less() (v1, v2)) return -1; //使用库函数代替"() (v2, v1)) return 1;
return 0;
}
template[u]
int compare (const char (&p1) [N], const char (&p2) [M])
{
std::cout
作者:csdn博客 Spike_King
更多精彩内容:http://www.bianceng.cn/Programming/cplus/
|
|