模板函数
#include<iostream>
using namespace std;
#include<string>
template<typename T1,typename T2>
bool compare(T1& p1, T2& p2) {
if (p1==p2)
{
return true;
}
else
{
return false;
}
}
template<typename T1, typename T2>
T1 add(T1& p1, T2& p2) {
return p1 + p2;
}
template<typename T>
T add01(T &p1, T& p2) {
return p1 + p2;
}
int add02(int a, int b) {
return a + b;
}
class Person
{
public:
Person(int age, string name) {
this->age = age;
this->name = name;
};
int age;
string name;
};
template<> bool compare(Person& p1, Person& p2) {
if (p1.age==p2.age&&p1.name==p2.name)
{
return true;
}
else
{
return false;
}
}
void test() {
char db='c';
int a = 20;
if (compare(a, db)) {
cout << "a=db" << endl;
}
else
{
cout << "a!=db" << endl;
}
}
void test01() {
char db = 'c';
int a = 20;
cout << "普通函数调用" << add02(a, db);
cout <<"定义两个typename" << add(a, db)<<endl;
cout <<"指定类型" << add<int>(a, db)<< endl;
}
int main() {
Person p1(10, "abc");
Person p2(10, "abc");
if (compare(p1, p2)) {
cout << "p1p2相等" << endl;
};
Person p3(11, "abc");
Person p4(10, "abc");
compare(p3, p4);
if (!compare(p3, p4)) {
cout << "p3p4不相等" << endl;
};
test();
test01();
return 0;
}
模板类
#include<iostream>
#include<string>
using namespace std;
template<class T1, class T2=int>
class Person
{
public:
Person(T1 name, T2 age)
{
this->age = age;
this->name = name;
};
T1 name;
T2 age;
private:
};
class Person1
{
public:
void showPerson1() {
cout << "showPerson1" << endl;
}
};
class Person2
{
public:
void showPerson2() {
cout << "showPerson2" << endl;
}
};
template<class T>
class man {
public:
T obj;
void func1(){
obj.showPerson1();
}
void func2() {
obj.showPerson2();
}
};
int main() {
Person<string> p1("adc", 18);
cout << p1.age << p1.name;
man<Person1> man1;
man1.func1();
return 0;
}
|