天天看点

[C++11]使用using和typedef给模板定义别名

using语法和typedef一样,并不会创建出新的类型,它们只是给某些类型定义了新的别名。using相较于typedef的优势在于定义函数指针别名时看起来更加直观,并且可以给模板定义别名。

使用typedef给模板定义别名:

无法直接使用typedef给模板定义别名

代码如下:

template<typename T>
typedef map<int, T>mapType;//error
           

注意:使用typedef给模板定义别名,需要用到struct

代码如下:

#include <iostream>
#include <string>
#include <map>
using namespace std;

template<typename T>
struct myMap
{
	typedef map<int, T>mapType;
};


template<typename T>
class Container
{
public:
	void print(T & t)
	{
		auto it = t.begin();
		for (; it != t.end(); it++)
		{
			cout << it->first << " " << it->second << endl;
		}
	}
};

int main()
{
	myMap<int>::mapType mm1;
	mm1.insert(make_pair(1, 1));
	mm1.insert(make_pair(2, 2));
	mm1.insert(make_pair(3, 3));

	Container<myMap<int>::mapType> q;
	q.print(mm1);

	myMap<double>::mapType mm2;
	mm2.insert(make_pair(1, 1.1));
	mm2.insert(make_pair(2, 2.2));
	mm2.insert(make_pair(3, 3.3));

	Container<myMap<double>::mapType> q1;
	q1.print(mm2);

	myMap<string>::mapType mm3;
	mm3.insert(make_pair(3, "Tom"));
	mm3.insert(make_pair(2, "Jack"));
	mm3.insert(make_pair(1, "Hello"));

	Container<myMap<string>::mapType> q2;
	q2.print(mm3);

	return 0;
}
           

测试结果:

[C++11]使用using和typedef给模板定义别名

使用using给模板定义别名:

代码如下:

#include <string>
#include <iostream>
#include <map>
using namespace std;


template<typename T>
class Container
{
public:
	void print(T & t)
	{
		auto it = t.begin();
		for (; it != t.end(); it++)
		{
			cout << it->first << " " << it->second << endl;
		}
	}
};


template<typename T>
using myMap = map<int, T>;


int main()
{
	myMap<string> mm3;
	mm3.insert(make_pair(1, "Tom"));
	mm3.insert(make_pair(2, "jack"));
	mm3.insert(make_pair(3, "hello"));
	Container<myMap<string>> t;
	t.print(mm3);
	return 0;
}
           

测试结果:

[C++11]使用using和typedef给模板定义别名

继续阅读