有没有一个好的方法来设置C / C ++成员变量从字符串表示? (内省) [英] Is there a good way of setting C/C++ member variables from string representations? (introspection-lite)

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

问题描述

我有一个结构体有一些成员,我想能够从一个字符串获取和设置。由于C ++没有任何内省我需要一些创造性的解决方案与宏,stringize运算符和可能 boost :: bind。我不需要完全序列化或

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'

我想要有这样的东西:

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")

一个巨大的 if 语句。

任何想法如果有一个整洁的解决方案?

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

相关问题: http://stackoverflow.com/questions/1540114/object-reflection

编辑:
感谢maxim1000的'map to int Type :: *'技巧 - 这对我有用:

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;

这篇关于有没有一个好的方法来设置C / C ++成员变量从字符串表示? (内省)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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