c++ 基础知识-模板2
1.普通函数与函数模板的调用规则
1.如果函数模板和普通函数都可以实现,优先使用普通函数
2.可以通过空模板参数列表来强制调用函数模板
3.函数模板可以发生重载
4.如果函数模板可以产生更好的匹配,优先调用函数模板
#include <iostream>
using namespace std;
void myPrint(int a, int b)
{
cout<<"普通函数"<<endl;
cout<<"a:"<<a<<"b:"<<b<<endl;
}
template <class T>
void myPrint(T a, T b)
{
cout<<"模板函数"<<endl;
cout<<"a:"<<a<<"b:"<<b<<endl;
}
template <class T>
void myPrint(T a, T b,T c)
{
cout<<"模板函数"<<endl;
cout<<"a:"<<a<<"b:"<<b<<"c:"<<c<<endl;
}
void test_fun()
{
int a = 1;
int b = 2;
int c = 3;
//1.如果函数模板和普通函数都可以实现,优先使用普通函数
myPrint(a,b);
//2.可以通过空模板参数列表来强制调用函数模板
myPrint<>(a,b);
//3.函数模板可以发生重载
myPrint(a,b,c);
int d = '1';
int e = '2';
//4.如果函数模板可以产生更好的匹配,优先调用函数模板
myPrint(d,e);
//输出
// 普通函数
//a:1b:2
// 模板函数
//a:1b:2
// 模板函数
//a:1b:2c:3
// 普通函数
//a:49b:50
}
int main()
{
test_fun();
return 0;
}
2.类模板基本语法
#include <iostream>
#include <string>
using namespace std;
//类模板
template<class ageType,class nameType>
class Person
{
public:
Person(ageType age,nameType name)
{
this->m_age = age;
this->m_name = name;
}
ageType m_age;
nameType m_name;
};
void test_fun()
{
Person<int ,string> p1(12,"jkjkjk");
cout<<p1.m_age<<endl;
cout<<p1.m_name<<endl;
}
int main()
{
test_fun();
return 0;
}
3.类模板的成员函数是调用的时候才可以创建
#include <iostream>
using namespace std;
//类模板的成员函数是调用的时候才可以创建
class Person1
{
public:
void showPerson1()
{
//构造函数
cout<<"Person1"<<endl;
}
};
class Person2
{
public:
void showPerson2()
{
//构造函数
cout<<"Person2"<<endl;
}
};
template <class T>
class myPerson
{
public:
T obj;
void fun1()
{
obj.showPerson1();
}
void fun2()
{
obj.showPerson2();
}
};
void test()
{
myPerson<Person1>p;
p.fun1();
//p.fun2();//error C2039: “showPerson2”: 不是“Person1”的成员
}
int main()
{
test();
return 0;
}
4.类模板对象做函数参数
#include <iostream>
#include <string>
using namespace std;
//通过类模板创建的对象,可以有三种方式向函数中进行传参
//使用比较广泛的是指定传入的类型
template <class T1,class T2>
class Person
{
public:
Person(T1 name,T2 age)
{
this->m_name = name;
this->m_age = age;
}
public:
T1 m_name;
T2 m_age;
};
//指定传入类型
void showInfo(Person<string,int> &p)
{
cout<<"name:"<<p.m_name<<endl;
cout<<"age:"<<p.m_age<<endl;
}
void test()
{
Person<string,int>p("hh",123);
showInfo(p);
}
int main()
{
test();
return 0;
}
5.类模板与继承
#include <iostream>
#include <string>
using namespace std;
//模板类,基类
template<class T>
class Base
{
public:
//T obj;
Base()
{
cout<<"Base()"<<endl;
}
};
//类模板,子类
template<class T1,class T2>//T1表示子类,T2表示父类
class Son:public Base<T2>
{
public:
//T1 obj;
Son()
{
cout<<"Son()"<<" "<<typeid(T1).name()<<endl;
cout<<"Base()"<<" "<<typeid(T2).name()<<endl;
}
};
void test()
{
Son<int,string>s;
}
int main()
{
test();
return 0;
}