作业帮 > 综合 > 作业

高分求C++ boost库 BOOST_AUTO宏的原理,

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/29 23:55:04
高分求C++ boost库 BOOST_AUTO宏的原理,
在vs2008环境,boost库(忘了什么版本了)
#include
using namespace std;
int test()
{
static int a = 0;
++ a;
return a;
}
int main()
{
BOOST_AUTO(b,test());
int a = 0;
++ a;
//test();
}
宏展开是boost::type_of::msvc_typeid_wrapper::type b = test();
编译结果只有两句话
0041140E call test (41107Dh)
00411413 mov dword ptr [b],eax
跟 int b = test();是一样的.
那么,boost::type_of::msvc_typeid_wrapper::type是怎么变成int的呢
主要是利用模板片特化,
模板参数不仅仅可以实现还能是整形数
你看这个
template
struct msvc_typeid_wrapper {
typedef msvc_typeid_wrapper type;
};
它实际上就是一个片特化,如果模板参数是1(这个1往往又利用枚举的值来传递),至于变成int,主要是是下面的宏与条件编译联合作用的结果
# define BOOST_TYPEOF_NESTED_TYPEDEF_TPL(name,expr) \
struct name {\
BOOST_STATIC_CONSTANT(int,_typeof_register_value=sizeof(boost::type_of::typeof_register_type(expr)));\
typedef typename boost::type_of::msvc_extract_type::id2type id2type;\
typedef typename id2type::type type;\
};