14.3 Overloading Function Templates °函数模板可以被重载 °允许有其它同名的函数模板,但参数不同 °允许有其它同名的函数,但参数不同 °编译器挑选最佳匹配的函数或模板 °编译器通过匹配过程确定调用哪个函数。 °首先,编译器寻找和使用最符合函数名和参数类型 的函数调用。如果找不到,则检查是否可以用函数 模板产生符合函数名和参数类型的模板函数。 °如果有多个函数和调用函数相匹配(且匹配程度相 同),编译器会认为有二义性,将产生编译错误 °如果没有找到符合函数,将考虑调用强制类型转换 0 2018, SEU. All rights reserved. 16
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 16 14.3 Overloading Function Templates 函数模板可以被重载 允许有其它同名的函数模板,但参数不同 允许有其它同名的函数,但参数不同 编译器挑选最佳匹配的函数或模板 编译器通过匹配过程确定调用哪个函数。 首先,编译器寻找和使用最符合函数名和参数类型 的函数调用。如果找不到,则检查是否可以用函数 模板产生符合函数名和参数类型的模板函数。 如果有多个函数和调用函数相匹配(且匹配程度相 同),编译器会认为有二义性,将产生编译错误 如果没有找到符合函数,将考虑调用强制类型转换
#include <iostream> using namespace std template <class t> void print (const T &a, int b)(cout < first function called! "< end丹} template <class t, class t1> ctie 1c: \users\dftalent \documents\visual studio2010 projectstest\test\test.cp(26): error c2668:“ print”:对重载函数的调用不明确 c: \users\dftalent\ documents\visual studio2010 projects\test\test\test.cp11):可能是“ void print(int,int〉( const t&,Tl,int)” vith 1〉 Tint, Tl=int c: \users\dftalent\ documents\visual studio 2010\projects\test\test\test. cpp(11): s* "void print (int, int>(const T&, int, T1 T=int Tl=int 尝试匹配参数列表“int,int,int)”时 void print (int a)(cout < fifth function called! <endl丹} prf m:i fF n ti n called print (1, 2); print(1.1, 2); o 2018, SEU. All rights reserved. 17
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 17 #include <iostream> using namespace std; template <class T> void print (const T &a, int b) {cout << "first function called!"<< endl;} template <class T, class T1> void print (const T &a, T1 b) {cout << "second function called!";} template <class T, class T1> void print (const T &a, int c, T1 b) {cout << " third function called!";} template <class T, class T1> void print (const T &a, T1 b, int c) {cout << “fourth function called!";} void print (int a, int b) {cout << " fifth function called!"<< endl;} void print (int a ) {cout << “sixthfunction called!"<< endl;} print(1,2); print(1.1, 2); print(1,2,3);
Topics o 14.1 Introduction o 14.2 Function Templates o 14.3 Overloading Function Templates 14. 4 Class Templates o 14.5 Nontype Parameters and Default Types for Class Templates o 14.6 Notes on Templates and Friends o 14.7 Notes on Templates and static Members 0 2018, SEU. All rights reserved. 18
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 18 Topics 14.1 Introduction 14.2 Function Templates 14.3 Overloading Function Templates 14.4 Class Templates 14.5 Nontype Parameters and Default Types for Class Templates 14.6 Notes on Templates and Friends 14.7 Notes on Templates and static Members