设为首页 加入收藏

TOP

C++中模拟反射填充消息struct(二)
2014-11-24 01:40:33 来源: 作者: 【 】 浏览:5
Tags:模拟 反射 填充 消息 struct
eld_0_c),


field_1_e_type(&field_1_c),


field_2_e_type(&field_2_c)


));



if(matched){


Event::fill(e,field_0_c);


Event::fill(e,field_1_c);


Event::fill(e,field_2_c);


return true;


}



return false;


};



到此,我们发现不同事件的成员数目是不同的,所以,上述伪代码只能适应成员数为3的消息。


那么,我们就需要提供一组fill实现,每个负责一个成员数。同样,使用模板参数和模板特化来实现:


template


bool fill(Msg* e);



template


bool fill<1,Msg>(Msg* e){


field_0_c_type field_0_c;



bool matched = p->match(make_e_tuple(


field_0_e_type(&field_0_c)


));



if(matched){


Event::fill(e,field_0_c);


return true;


}


return false;


};



template


bool fill<2,Msg>(Msg* e)


field_0_c_type field_0_c;


field_1_c_type field_1_c;


......



额~ 这不是又重复了吗?


别急,我们可以用boost::preprocess收敛这些实现,boost::preprocess用来生成重复的代码,


使用后,我们的fill方法长这样:


namespace aux {


template


struct fill_impl;


#define EMATCH_MAX_FIELD 8



#define BOOST_PP_ITERATION_LIMITS (1,8)


#define BOOST_PP_FILENAME_1


#include BOOST_PP_ITERATE()


};


template


struct fill : aux::fill_impl::type::value , FieldList>{


};



怎么回事?fill方法消失了?


不,并没有消失,我们把他隐藏在


e_match_impl.h



这个文件里,通过boost::preprocess重复include这个文件8次,从而获得1个到8个成员的fill实现。并通过集成把这个实现模板提供的功能暴露出来,同时收敛其模板参数。


至此,我们得到了一个可以根据FieldList(成员属性的mpl::list),自动match和填充C++结构的fill方法。




使用
好了,我们来写一段代码,测试一下上述实现吧:



struct SimpleObject{


bool b;


std::string s;


};



typedef boost::mpl::list<


auto_field,


auto_field


> SimpleObjectFields;




int _tmain(int argc, _TCHAR* argv[])


{


SimpleObject so;



const std::string remote_node_name("testnode@127.0.0.1");


const std::string to_name("reflect_msg");



tinch_pp::node_ptr my_node = tinch_pp::node::create("my_test_node@127.0.0.1", "abcdef");



tinch_pp::mailbox_ptr mbox = my_node->create_mailbox();



mbox->send(to_name, remote_node_name, tinch_pp::erl::make_e_tuple(tinch_pp::erl::atom("echo"), tinch_pp::erl::pid(mbox->self()), tinch_pp::erl::make_e_tuple(


tinch_pp::erl::make_atom("false"),


tinch_pp::erl::make_string("hello c++")


)));



const tinch_pp::matchable_ptr reply = mbox->receive();



bool ret = fill::fill_on_match(&so,reply);


printf("ret is %s \n",(ret "true":"false"));


printf("so.b == %s \n",(so.b "true":"false"));


printf("so.s == %s \n",so.s.c_str());


system("pause");


return 0;


}



由于我没有找到tinch_pp怎么构造一个matchable_ptr,所以需要一个erlang的外部节点把我构造的tuple反射回来,tinch_pp已经提供了这样的一个server,运行上述代码前,需要先把他启动起来:


view sourceprint 1 werl -pa . -sname testnode -setcookie abcdef



运行后,应该打印出:


ret is true


so.b == false


so.s == hello c++


请按任意键继续. . .



至此,我们实现了想要的功能,使用同一份代码(fill)将Erlang tuple直接填充到指定的C++结构中,而不必大量重复填充代码。


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇如何在Hadoop的MapReduce程序中处.. 下一篇MinGW 编译FFmpeg 1.2.1 的H.264 ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: