C++ - 函数模板(function template) 详解

模板(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;

}


 


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CarolineSpike

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值