模板(template) 详解
本文地址: http://blog.csdn.net/caroline_wendy/article/details/16866269
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 <iostream>
#include <vector>
#include <functional> //less<>
#include <cstring> //strcmp
template <typename T>
int compare (const T &v1, const T &v2)
{
if (std::less<T>() (v1, v2)) return -1; //使用库函数代替"<", 会避免指针地址比较
if (std::less<T>() (v2, v1)) return 1;
return 0;
}
template<unsigned N, unsigned M>
int compare (const char (&p1) [N], const char (&p2) [M])
{
std::cout << "N = " << N << " M = " << M << std::endl; //添加一个空终止符(null terminator)
return std::strcmp (p1, p2); //只比较不同的第一个字符
}
int main (void) {
std::cout << compare(1, 0) << std::endl;
std::vector<int> v1{1, 2, 3}, v2{4, 5, 6};
std::cout << compare(v1, v2) << std::endl;
std::cout << compare("girl", "lad") << std::endl;
int a[] = {1, 2, 3, 4}, b[] = {1, 3, 4, 5};
std::cout << compare(a, b) << std::endl;
return 0;
}