[size=x-large][color=blue]1、获取变量名称[/color][/size]
[size=large]采用如下宏定义即可,这个宏定义将表达式x直接转换为对应的字符串:[/size]
[size=large]用法:[/size]
[size=x-large][color=blue]2、获取类型名称[/color][/size]
[size=large]采用如下宏定义即可,这个宏定义将表达式x直接转换为对应的字符串:[/size]
[size=large]更多的用法见最后的程序;
[color=red]先看一下输出:[/color]
[/size]
[img]http://dl.iteye.com/upload/attachment/0078/1151/2b36910b-b1b7-3540-aef8-c3ab9e34e16d.png[/img]
[size=x-large][color=blue]3、参考的网址[/color][/size]
1、[url]http://www.cplusplus.com/reference/typeinfo/type_info/[/url]
2、[url]http://bbs.csdn.net/topics/380019977[/url]
[color=red][size=x-large]4、完整的程序:[/size][/color]
[size=large]采用如下宏定义即可,这个宏定义将表达式x直接转换为对应的字符串:[/size]
#define varName(x) #x
#define printExp(exp) cout<<#exp<<"为:\t\t"<<(exp)<<endl //这样就方便调试了,不用一个个的写变量名称了
[size=large]用法:[/size]
cout<<varName(aInt)<<endl; \\输出为: aInt
[size=x-large][color=blue]2、获取类型名称[/color][/size]
[size=large]采用如下宏定义即可,这个宏定义将表达式x直接转换为对应的字符串:[/size]
//可能需要#include <typeinfo> 好像不引用也成
cout<<typeid(int).name()<<endl;
[size=large]更多的用法见最后的程序;
[color=red]先看一下输出:[/color]
[/size]
[img]http://dl.iteye.com/upload/attachment/0078/1151/2b36910b-b1b7-3540-aef8-c3ab9e34e16d.png[/img]
[size=x-large][color=blue]3、参考的网址[/color][/size]
1、[url]http://www.cplusplus.com/reference/typeinfo/type_info/[/url]
2、[url]http://bbs.csdn.net/topics/380019977[/url]
[color=red][size=x-large]4、完整的程序:[/size][/color]
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
#define varName(x) #x
#define printExp(exp) cout<<#exp<<"为:\t\t"<<(exp)<<endl
#define printExpToString(exp) cout<<(string(#exp)+"为:\t\t") <<(exp).toString()<<endl //注意exp加个括号更安全
namespace LC {
template<typename T> class Base {
public:
virtual string toString() {
stringstream ss;
ss<<typeid(*this).name();
return ss.str();
}
Base operator+ (int a){
return *this;
}
};
template<typename T> class Derived:public Base<T> {
public:
virtual string toString() {
stringstream ss;
ss<<typeid(*this).name();
return ss.str();
}
};
}
typedef LC::Base<double> BaseDouble;
typedef LC::Derived<int> DerivedInt;
void main() {
int aInt=1;
printExp(aInt);
printExp(typeid(int).name());
printExp(typeid(aInt).name());
cout<<"变量名称为: "<<varName(aInt)<<endl;
cout<<endl;
BaseDouble base;
printExpToString(base);
printExpToString(base+5+4); //若宏定义中exp不加括号就无法编译了!!!
printExpToString((LC::Base<int>)DerivedInt());
cout<<endl;
DerivedInt derived;
LC::Base<int>* pBase=&derived;
LC::Base<int> baseCast=derived;
printExpToString(*pBase);
printExpToString(derived);
printExpToString(baseCast);
printExp(typeid(*pBase)==typeid(derived));
printExp(typeid(baseCast)==typeid(derived));
}