C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
来源:互联网 发布:php reset current 编辑:程序博客网 时间:2024/04/29 04:37
函数模板(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);elseret << " 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版本, 右值调用conststd::cout << debug_rep("hello world") << std::endl;return 0;}
输出:
"hi"pointer: 0x22fec4 hipointer: 0x22fec4 hiconst "hello world"
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- C++ - 成员函数(member function)模板(template) 详解 及 代码
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- 成员函数(member function)模板(template) 详解 及 代码
- 函数模板的重载(overload)
- C++ - 可变参数函数模板(Variadic Function Template) 详解 及 代码
- C++ - 函数模板(function template) 详解
- 函数模板 Function Template(C++Primer-10)
- 函数模板template-重载的模板
- 函数的重载(OVERLOAD)
- Python - 函数(function) 的 代码 及 详解
- c++之-----重载函数overload function
- C++笔记4--函数重载(function overload)
- 函数模板(Function Template)
- C++函数模板(function template)
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- C++ 函数模板的特化(Function Template Specialization)
- C++ Template学习笔记之函数模板(7)——重载函数模板
- 面向对象6_常见的设计模式【单例模式】【模板模式】【组合设计模式】等
- 开复老师的语录
- MTK6589双卡拨打电话选择哪张卡及获得默认卡的接口
- 你最喜欢的程序员漫画”精选
- proc文件系统
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- c/c++ 实现curl http地址
- header函数的作用
- 第14周项目一输出20个数,每5个换行
- JAXB--@XmlElementWrapper注解和泛型一起使用(三)
- 子makefile怎么向总控makefile传递变量
- mysql的调整
- 对数组的数进行排序
- mysql导入导出问题