c++模板 --- 模板的嵌套

简介

明白类型是什么即可,可以适当运用using语法起别名 简化代码。

一、函数模板嵌套

template <class _Ty1,class _Ty2>
class MM 
{
public:
	MM(_Ty1 one, _Ty2 two) :one(one), two(two) {}
	friend ostream& operator<<(ostream& out, const MM& mm) 
	{
		out << mm.one << " " << mm.two;
		return out;
	}
protected:
	_Ty1 one;
	_Ty2 two;
};
 
template <class _Ty>        //这个函数模板以另一个模板类型的数据为参数
void print(_Ty data) 
{
	cout << data << endl;   //需要运算符重载
}
int main() 
{
	//隐式调用
	print(MM<string, int>("小芳", 32));    //在用类模板时显式写出来
	//显示调用
	//函数模板可以隐式调用 但是需要知道自己传的是什么类型 模板类型:MM
	print<MM<string, int>>(MM<string, int>("小美", 28));
	//起别名简化代码
	using MMType = MM<string, int>;
    //显示调用优化
	print<MMType>(MMType("小美", 28));
	return 0;
}
 
/*输出*/
 
小芳 32
小美 28

二、类模板嵌套

template <class _Ty1,class _Ty2>
class MM 
{
public:
	MM(_Ty1 one, _Ty2 two) :one(one), two(two) {}
	friend ostream& operator<<(ostream& out, const MM& mm) 
	{
		out << mm.one << " " << mm.two;
		return out;
	}
protected:
	_Ty1 one;
	_Ty2 two;
};
 
template <class _Ty1,class _Ty2>    //再写一个类去操作数据
class Data 
{
public:
	Data(_Ty1 one, _Ty2 two) :one(one), two(two) {}
	void print() 
	{
		cout << one <<" "<< two << endl;
	}
protected:
	_Ty1 one;
	_Ty2 two;
};
void testFunc() 
{
//Data类的实例化   _Ty1 one: MM   _Ty2 two: MM
	Data<MM<string, int>, MM<double, double>> 
	data(MM<string, int>("小芳",18), MM<double, double>(89,56));
	data.print();    //传入两个对象 分别用 _Ty1 和 _Ty2 构造
 
	//上面两行 等效下面四行代码 先把对象构建出来再传入对象即可
	MM<string, int> mmData("小芳", 18);
	MM<double, double> mmScore(89, 56);
	Data<MM<string, int>, MM<double, double>> mData(mmData, mmScore);
	mData.print();
}
int main()
{
    testFunc();
}
 
/*输出*/
 
小芳 18 89 56
小芳 18 89 56

你可能感兴趣的:(C++,c++,开发语言)