#include<iostream> using namespace std; class Person { public: string name; int age; Person(string name,int age) { this->name = name; this->age = age; } }; //不支持判断自己定义的数据类型 //这里需传入引用 template<class T> bool myCompare(T &a, T &b) { if (a == b) { return true; } else { return false; } } template<> bool myCompare(Person& p1, Person& p2) { if (p1.name == p2.name && p1.age == p2.age) { return true; } else { return false; } } void test() { int a = 10; int b = 10; bool res = myCompare(a, b); cout << res << endl; Person p1("tom",10); Person p2("tom",10); //我们需要具体化Person版本的实现 bool res2 = myCompare(p1, p2); cout << res2 << endl; } int main() { test(); system("pause"); return 0; }
c++之函数模板的局限性
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:c++之模板-类模板
下一篇:c++之普通函数和模板函数的区别
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C++ 模板匹配matchTemplate
C++ 模板匹配matchTemplate
opencv 模版匹配 -
深度解读《深度探索C++对象模型》之C++虚函数实现分析(三)
本系列深入分析编译器对于C++虚函数的底层实现,最后分析C++在多态的情况下的性能是否有受影响,多态究竟有多大的性能损失。
虚函数 虚函数表 虚基类 C++性能分析 C++虚函数实现分析 -
C++模板的局限性
~~局限性:~~*模板的通用性并不是万能的例如:在上述代码中提供的赋值操作,入过传入的a和b
c++ 数据类型 #include 自定义类型 -
递归函数的局限性
递归函数在调用过程中会占用大量的计算机堆栈资源,所以在写程序过程中最好避免使用
c语言 c++ python 递归函数 for循环 -
公司的局限性html
-
c++模板之函数模板
技术是实现目标的手段和方式,模板的存在,是为了让程序猿能编写出与类型无关不是模板了
Data 函数体 函数模板 -
泛型的局限性
对于代码类似、雷同,只有参数、返回值类型不同程,当然可
泛型 泛型方法 泛型类