是否有从字符串再presentations设置C / C ++成员变量的好办法? (内省的精简版) [英] Is there a good way of setting C/C++ member variables from string representations? (introspection-lite)

查看:103
本文介绍了是否有从字符串再presentations设置C / C ++成员变量的好办法? (内省的精简版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了一些成员,我希望能够得到与字符串设定一个结构。由于C ++没有任何反省我想我需要一些宏创造性的解决方案,运营商stringize,也许的boost ::绑定。我不需要完全的序列化或自省,更是内省的精简版

我想沿着这个线的东西:

 结构的MyType {
  INT FIELDA;
  INT fieldB;
};
DECLARE_STRING_MAP(的MyType,FIELDA);
DECLARE_STRING_MAP(的MyType,fieldB);MyType的吨;
SET_VALUE_FROM_STRING(MyType的,叔,FIELDA,3)

而不是有一个巨大的如果语句。

如果有一个很好地解决了这个任何想法?

相关问题:<一href=\"http://stackoverflow.com/questions/1540114/object-reflection\">http://stackoverflow.com/questions/1540114/object-reflection

编辑:
由于maxim1000为'映射到int类型:: *'绝招 - 这个工作对我来说:

 的#define DEFINE_LOOKUP_MAP(类型)的std ::地图&LT; AnsiString类型,int类型:: *&GT;映射器
#定义ADD_FIELD_MAPPING(类型,字段)映射器[#Field] =&放大器;类型::场
#定义SET_FIELD_FROM_MAP(类型,字段,VAR值)变种*(映射器[#Field)=值DEFINE_LOOKUP_MAP(的MyType);
ADD_FIELD_MAPPING(的MyType,FIELDA);
ADD_FIELD_MAPPING(的MyType,fieldB);SET_FIELD_FROM_MAP(MyType的,FIELDA,OBJ,3);


解决方案

如果他们都具有相同的类型,可以使用这样的:

 的std ::地图&LT;的std ::字符串,整数的MyType :: *&GT;映射器;
映射器[FIELDA] =&放大器;的MyType :: FIELDA;
映射器[fieldB] =&放大器;的MyType :: fieldB;
...
MyType的OBJ;
。OBJ *(映射器[FIELDA])= 3;

I've got a struct with some members that I want to be able to get and set from a string. Given that C++ doesn't have any introspection I figure I need some creative solution with macros, the stringize operator and maybe boost::bind. I don't need full serialization or introspection, more an 'introspection-lite'

I'd like to have something along the lines of this:

struct MyType {
  int  fieldA;
  int  fieldB;
};
DECLARE_STRING_MAP(MyType,fieldA);
DECLARE_STRING_MAP(MyType,fieldB);

MyType t;
SET_VALUE_FROM_STRING(MyType,t,"fieldA","3")

Rather than have a huge if statement.

Any idea if there's a neat solution to this?

Related question: http://stackoverflow.com/questions/1540114/object-reflection

EDIT: Thanks to maxim1000 for the 'map to int Type::*' trick -- this worked for me:

#define DEFINE_LOOKUP_MAP(Type) std::map<AnsiString,int Type::*> mapper 
#define ADD_FIELD_MAPPING(Type, Field) mapper[#Field]=&Type::Field 
#define SET_FIELD_FROM_MAP(Type, Field, var, value) var.*(mapper[#Field])=value    

DEFINE_LOOKUP_MAP(MyType); 
ADD_FIELD_MAPPING(MyType, fieldA); 
ADD_FIELD_MAPPING(MyType, fieldB); 

SET_FIELD_FROM_MAP(MyType, fieldA, obj, 3);

解决方案

If all of them have the same type, you can use something like this:

std::map<std::string,int MyType::*> mapper;
mapper["fieldA"]=&MyType::fieldA;
mapper["fieldB"]=&MyType::fieldB;
...
MyType obj;
obj.*(mapper["fieldA"])=3;

这篇关于是否有从字符串再presentations设置C / C ++成员变量的好办法? (内省的精简版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆