C++中的 template 可以用来声明函数模板和类模板,讲到函数模板,就难免想到参数默认值。
以下是几个例子,用来说明,template中参数默认值的使用。
-
- 按照最初的设想,直接在函数声明处给参数赋默认值。无法通过编译,会提示无法找到对应的函数声明。如例1。
- 发现是无法生成默认值对应的模板函数,给模板函数的类型也赋默认值后,能够正常生成形如void print(T, Ts&)的函数。其中,类型Ts的默认值要与参数os的默认值相符合。如例2。
- 对于类模板中的函数,则不存在类似的问题。因为类模板必须指明模板参数的类型。如例3。
例1:
#include<iostream> using namespace std; template<typename T,typename Ts>//没有给Ts赋默认值 void print(T input,Ts& os=cout){ os<<input<<endl; } int main(){ print("hello template"); return 0; }
编译报错如下:
test4template.cpp: In function ‘int main()’: test4template.cpp:11:24: error: no matching function for call to ‘print(const char [15])’ print("hello template"); ^ test4template.cpp:6:6: note: candidate: template<class T, class Ts> void print(T, Ts&) void print(T input,Ts& os=cout){ ^ test4template.cpp:6:6: note: template argument deduction/substitution failed: test4template.cpp:11:24: note: couldn't deduce template parameter ‘Ts’ print("hello template"); ^
例2:
#include<iostream> using namespace std; template<typename T,typename Ts=ostream> void print(T input,Ts& os=cout){ os<<input<<endl; } int main(){ print("hello template"); return 0; }
能够正常编译运行,运行结果如下:
hello template 按回车键返回
例3:
#include<iostream> using namespace std; template<typename T,typename Ts=ostream> void print(T input,Ts& os=cout){ os<<input<<endl; } template<typename T,typename Ts> class printDao{ public: printDao(){} static void print(T input,Ts& os=cout){ os<<input<<endl; } }; int main(){ print("hello template"); printDao<string,ostream> p; p.print("hello template in class"); return 0; }
运行结果:
hello template hello template in class 按回车键返回