Axe*_*xel 3 c++ templates struct
基本上,我有很多不同类型的结构,如下所示:
typedef struct
{
char memberA;
int memberB;
...
} tStructA;
Run Code Online (Sandbox Code Playgroud)
是否可以使用模板从结构中获取/提取任意成员?在伪代码中,我正在寻找这样的东西:
/*This is pseudocode!*/
template <typename STRUCT_TYPE, typename MEMBER_TYPE, membername NAME>
class cMemberExtractor
{
public:
MEMBER_TYPE
extract(const STRUCT_TYPE* pStruct) const
{
return pStruct->NAME;
}
};
Run Code Online (Sandbox Code Playgroud)
背后的想法是使用这样的模板:
/*somewhere*/
void
producer()
{
//produce update
tStructA* pUpdate=new tStructA;
...
//send update to receivers
emit(pUpdate);
}
/*elsewhere*/
void
consumer(const tStructA* pUpdate)
{
//extract data
int data=cMemberExtractor<tStructA,int,memberB>().extract(pUpdate);
//process data
...
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!
您可以不使用名称而是使用成员指针来做到这一点:
\n\ntemplate <typename\xc2\xa0C,\xc2\xa0typename\xc2\xa0M>\nstruct\xc2\xa0updater_t {\n typedef M C::*member_ptr_t;\n\n updater_t( member_ptr_t ptr, M const & new_value )\n : new_value( new_value ), ptr(ptr)\n {}\n updater_t( member_ptr_t ptr, C & original )\n : new_value( original.*ptr ), ptr(ptr)\n {}\n void operator()( C & obj ) {\n obj.*ptr = new_value;\n }\n M new_value;\n member_ptr_t ptr;\n};\nstruct test {\n int value;\n};\nint main() {\n updater_t<test,int> update( &test::value, 10 );\n test object;\n update( object );\n\n test object2;\n updater_t<test,int> update_copy( &test::value, object );\n update_copy( object2 );\n}\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:按照 litb 的建议将成员指针移动到模板参数:
\n\ntemplate <typename\xc2\xa0C,\xc2\xa0typename\xc2\xa0M, M C::* Ptr>\nstruct\xc2\xa0updater_t {\n updater_t( M const & new_value ) : new_value( new_value ) {}\n updater_t( member_ptr_t ptr, C & original ) : new_value( original.*Ptr ) {}\n void operator()( C & obj ) {\n obj.*ptr = new_value;\n }\n M new_value;\n};\nint main() {\n updater_t<test,int, &test::value> update( 10 );\n test object;\n update( object );\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1128 次 |
| 最近记录: |