C++编程思想 第2卷 第5章 深入理解模板 模板参数 默认模板参数

博客介绍了函数模板使用中的情况,虽不能在函数模板中用默认模板参数,但可用模板参数作普通函数默认参数。函数模板在参数列表加元素输出,sum()第3个参数是累积运算初始值,省略时默认是T(),如int等系统固有类型。

尽管不能在函数模板中使用默认的模板参数
却能够用模板参数作为普通函数的默认参数
函数模板在参数列表中加入一个元素

//: C05:FuncDef.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
using namespace std;

template<class T> T sum(T* b, T* e, T init = T()) {
  while(b != e)
    init += *b++;
  return init;
}

int main() {
  int a[] = { 1, 2, 3 };
  cout << sum(a, a + sizeof a / sizeof a[0]) << endl; // 6
  getchar();
} ///:~

输出
6

sum()的第3个参数是作为对这些元素进行累积运算的初始值
由于省略了第三个参数
参数就默认认为是T()
在这里是int或其他系统固有的类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值