C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
2013-11-28 18:29
681 查看
函数模板(function template) 的 重载(overload) 详解 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17010031函数模板(function template)重载, 即实例化特定的模板, 确定T的类型, 选择匹配度最高的一个;
需要注意传递的具体类型, 如传递的是"&s", 则表示"string* t = &s", 即实际匹配的类型为"string* t";
当非函数模板和函数模板匹配度相同时, 优先选择非函数模板;
调用模板时, 一定要注意顺序, 或者提前声明, 以保证可以找到函数模板, 进行实例化;
具体参见代码注释, 代码如下:
/* * cppprimer.cpp * * Created on: 2013.11.28 * Author: Caroline */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <sstream> #include <string> #include <utility> using namespace std; template <typename T> std::string debug_rep (const T &t) { std::ostringstream ret; ret << t; return ret.str(); } template <typename T> std::string debug_rep (T *p) { std::ostringstream ret; ret << "pointer: " << p; if (p) ret << " " << debug_rep (*p); else ret << " null pointer"; return ret.str(); } /*非模板函数*/ std::string debug_rep (const string &s) { return '"' + s + '"'; } /*char 重载版本*/ std::string debug_rep (char *p) { std::cout << "plain "; return debug_rep (std::string(p)); } /*const char 重载版本*/ std::string debug_rep (const char *p) { std::cout << "const "; return debug_rep (std::string(p)); //调用第一个模板, 注意顺序, 或者前置声明 } int main (void) { std::string s("hi"); std::cout << debug_rep (s) << std::endl; //调用第一个 / 优先调用非模板 //&s, 即 string* s = &s, string* t = const T &t, 即 T->string* // string* t = T* t, 即 T->string; 所以选择第二个 std::cout << debug_rep (&s) << std::endl; //调用第二个 const std::string *sp = &s; std::cout << debug_rep (sp) << std::endl; //调用第二个 //调用第二个, 只传递首字母; 包含char版本, 右值调用const std::cout << debug_rep("hello world") << std::endl; return 0; }
输出:
"hi" pointer: 0x22fec4 hi pointer: 0x22fec4 hi const "hello world"
本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387991
相关文章推荐
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- C++ - 成员函数(member function)模板(template) 详解 及 代码
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- C++ - 成员函数(member function)模板(template) 详解 及 代码
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- C++ - 函数模板(function template) 详解
- C++ - 函数模板(function template) 详解
- C++ 函数模板(十四)--template 泛型函数模板、通用函数、重载模板
- C++ 函数模板的特化(Function Template Specialization)
- C++ - 可变参数函数模板(Variadic Function Template) 详解 及 代码
- C++ - 函数模板(function template)返回值
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- C++ - 可变参数函数模板(Variadic Function Template) 详解 及 代码
- C++ - 函数模板(function template)返回值
- C++ - 函数模板(function template)右值引用参数 问题 及 解决
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- C++ - 函数模板(function template)右值引用参数 问题 及 解决
- 成员函数(member function)模板(template) 详解 及 代码
- C++中的四个默认成员函数与运算符重载详解
- C++ - 非类型模板参数(nontype template parameters) 使用 及 代码