尽管不能在函数模板中使用默认的模板参数
却能够用模板参数作为普通函数的默认参数
函数模板在参数列表中加入一个元素
//: 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或其他系统固有的类型