#include <iostream>
#include<string>
using namespace std;
//#define putongfangfa
#define muban
#ifdef putongfangfa
void Print(int a )
{
std::cout << a << std::endl;
}
void Print(string a )
{
std::cout << a << std::endl;
}
void Print(float a )
{
std::cout << a << std::endl;
}
int main()
{
//如果想用类似Print()函数打印不同数据类型的数据,需要分别实现三个函数,
//而这三个函数之间唯一的区别就是参数类型不同,如上面所示
Print(5);
Print("hello world");
Print(5.5f);
int b;
std::cin >> b;
return 0;
}
#endif
#ifdef muban
/*模板的使用情景一:在某些数据类型,尤其是函数参数类型不确定的情况下,可以使用此方法。
//三个函数,仅仅因为数据类型的不同,就需要写三个函数效率是比较低下的,这就是模板的意义之一。
template <typename T> //template <class T> 将typename代替成class也可以。
void Print(T a)
{
cout << a << endl;
}
void Print(int a ) //冲突的时候,优先选择非模板的函数。
{
std::cout << 666 << std::endl;
}
int main()
{
//第一种调用方法
Print<int>(4);
Print<string>("hello world2");
Print<float>(5.6);
//第二种调用方法
Print(5);
Print("hello world");
Print(5.5f);
int b;
std::cin >> b;
return 0;
}
*/
//模板的使用情景二:在某些数组的应用中,数据类型不确定,数组大小不确定,可以使用此方法。
//数组大小不确定。
/*template<int N>
class array
{
public:
int arr[N];
int getSize()
{
return N;
}
};
int main()
{
array<6> a;
cout << a.getSize() << endl;
int b = 0;
cin >> b;
return 0;
}*/
// 数组类型不确定,大小也不确定
template<typename T, int N>
class array
{
public:
T arr[N];
int getSize()
{
return N;
}
};
int main()
{
array<int, 8> a;
cout << a.getSize() << endl;
for(int i = 0; i < a.getSize(); i++ )
{
cout << a.arr[i] << " ";
}
int b = 0;
cin >> b;
return 0;
}
#endif