高分求C++ boost库 BOOST_AUTO宏的原理,有满意答案加分你懂得

在vs2008环境,boost库(忘了什么版本了)

#include <boost/typeof/typeof.hpp>
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<sizeof(*boost::type_of::encode_start(test()))>::type b = test();
编译结果只有两句话

0041140E call test (41107Dh)
00411413 mov dword ptr [b],eax
跟 int b = test();是一样的。
那么,boost::type_of::msvc_typeid_wrapper<sizeof(*boost::type_of::encode_start(test()))>::type是怎么变成int的呢

第1个回答  2012-09-14
主要是利用模板片特化,
模板参数不仅仅可以实现还能是整形数
你看这个
template<>
struct msvc_typeid_wrapper<1> {
typedef msvc_typeid_wrapper<1> 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<name>(expr)));\
typedef typename boost::type_of::msvc_extract_type<name>::id2type id2type;\
typedef typename id2type::type type;\
};本回答被提问者采纳
相似回答