C++中typedef和模板能否同时使用

1、程序的处理的步骤

步骤

所进行的内容

生成的文件

预处理

展开头文件/宏替换/去掉注释/条件编译

.i”文件

编译

检查语法,生成汇编

.s”文件

汇编

汇编代码转换机器码

.o”目标文件

链接

链接到一起生成可执行程序

.out”或“.exe”可执行文件

  • define:预处理期间处理,实际上所有的带#的都是在预处理期间处理的。
  • typedef:编译期间处理。
  • template:模板的实例化类型确定是在编译期间,模板实例化只会实例化用到的部分,没有用到的部分将不会被实例化。

例1:

#include <iostream>
#include <set>

using namespace std;

template<class T>
class A
{
public:
	A() {}
	~A() {}
	void add(T &t) {
		key.insert(t);
	}
	void display() {
		for(auto &var : key) {
			cout << var << " ";
		}
		cout << endl;
	}

protected:
	typedef set<T> mySet;

private:
	mySet key;
};

int main()
{
	//A<int> a;
	//for (int i = 0; i < 5; i++) {
	//	a.add(i);
	//}
	//a.display();	
system("pause");
	return 0;
}

出:

       可以看出以上程序编译通过并成功运行,因为typedef定义类型转变的时候必须是已经定义的类型,而template<class T>可以看作是对T做了定义,故可直接使用。

例2:

修改例1代码:

#include <iostream>
#include <set>

using namespace std;

typedef set<T> mySet;		// 错误

template<class T>
class A
{
public:
	A() {}
	~A() {}
	void add(T &t) {
		key.insert(t);
	}
	void display() {
		for(auto &var : key) {
			cout << var << " ";
		}
		cout << endl;
	}

private:
	mySet key;
};

int main()
{
	A<int> a;
	for (int i = 0; i < 5; i++) {
		a.add(i);
	}
	a.display();

	system("pause");
	return 0;
}

       以上代码编译出错,出错原因为“未定义标识符T”。因为typedef在类外,首先运行该typedef语句,而T是未定义类型,故而出错。因此在C++中判断typedef和模板能否同时使用关键是要判断两者的前后定义顺序。

原创文章 99 获赞 68 访问量 3万+

猜你喜欢

转载自blog.csdn.net/King_weng/article/details/105052560
今日推荐