首页 > 编程 > C++ > 正文

C/C++ 用宏定义实现简单泛型的功能

2019-11-10 22:15:50
字体:
来源:转载
供稿:网友
#include <iostream>#include <cstdio>#include <cstdlib>#include <assert.h>using namespace std;//宏定义实现泛型//在宏定义中出现#和##,通常起到下面的作用:// #表示:对应变量字符串化// ##表示:把宏参数名与宏定义代码序列中的标识符连接在一起,形成一个新的标识符#define GNERIC_STACK(STACK_TYPE,SUFFIX,STACK_SIZE)  /	static STACK_TYPE stack##SUFFIX[STACK_SIZE];    /	static int top_element##SUFFIX=-1;			    /	bool is_empty##SUFFIX(){						/		return top_element##SUFFIX==-1;			    /	}                       					    /													/	bool is_full##SUFFIX(){							/		return top_element##SUFFIX==STACK_SIZE-1;	/	}												/													/	void push##SUFFIX(STACK_TYPE val){				/		assert(!is_full##SUFFIX());					/		top_element##SUFFIX+=1;						/		stack##SUFFIX[top_element##SUFFIX]=val;		/	}												/													/	void pop##SUFFIX(){								/		assert(!is_empty##SUFFIX());				/		top_element##SUFFIX-=1;						/	}												/													/	STACK_TYPE top##SUFFIX(){						/		assert(!is_empty##SUFFIX());   				/		return stack##SUFFIX[top_element##SUFFIX];	/	}//注意,下面的宏定义式子不能放到main()函数内,因为这个宏定义展开后包含其他函数的定义,故不能//宏定义生成两个不同类型的堆栈//其结尾加不加';'都可以,注意下面的宏定义会被展开成什么(文本替换)GNERIC_STACK(int,_int,10)//##起到连接作用,比如is_empty##SUFFIX(),SUFFIX为_int,即最后生成is_empty_int()GNERIC_STACK(double,_double,10)//同上void test(){	push_int(5);	push_int(10);	push_int(22);	push_double(22.2);	push_double(-33.3);	push_double(-45.4);	while(!is_empty_int()){		cout<<top_int()<<" ";		pop_int();	}	cout<<endl;	while(!is_empty_double()){		cout<<top_double()<<" ";		pop_double();	}	cout<<endl;}int main() {	test();	return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选