1. C 风格字符串指针和字符串字面常量
cout « debug_rep ("hi world!" ) << endl; / / 调用 debug_rep (T* )
三个 debug_rep 版本都可行
• debug_rep (const T&)// T 被绑定到char [10 ]。
• debug_rep (T*) // T 被绑定到 const char。//T更加实例化 , 编译器会选择它。
• debug_rep (const string&)//要求从 const char到string的类型转换。
对给定实参来说, 两个模板都提供精确匹配一第二个模板需要进行一次( 许可的) 数组到指针的转换, 而对于函数匹配来说, 这种转换被认为是精确匹配。 非模板版本是可行的, 但需要进行一次用户定义的类型转换, 因此它没有精确匹配那么好, 所以两个模板成为可能调用的函数。
1.1 如果我们希望将字符指针按 string 处理, 可以定义另外两个非模板重载版本:
//将字符指针转换为 string, 并调用 string 版本的 debugstring debug_rep (char *p){return debug_rep (string (p) );}string debug_rep (const char * p ){return debug_rep (string (p) ) ;}
1.2 缺少声明可能导致程序行为异常
debug_rep (const string&) 的声明必须在作用域中。 否则, 就可能调用错误的debug_rep 版本:
( 代码不会编译失败)
template <typename T> string debug_rep (const T &t );template <typename T> string debug_rep (T *p);//为了使 debug_rep (char* ) 的定义正确工作, 下面的声明必须在作用域中string debug_rep (const string &);string debug_rep (char *p){// 如果接受一个 const strings的版本的声明不在作用域中,// 返回语句将调用 debug_rep (const T & ) 的 T 实例化为 string 的版本return debug_rep (string (p) );}