C++ 在C++;是否仍然可以通过字符串调用对象属性?

C++ 在C++;是否仍然可以通过字符串调用对象属性?,c++,C++,假设我有一个定义如下的对象: struct Something { int attribute1; string attribute2; } struct Something { int attribute1; std::string attribute2; }; void set_attr1(Something &obj, const std::string &value) { std::istringstream iss(value

假设我有一个定义如下的对象:

struct Something
{
    int attribute1;
    string attribute2;
}
struct Something
{
    int attribute1;
    std::string attribute2;
};

void set_attr1(Something &obj, const std::string &value)
{
    std::istringstream iss(value);
    iss >> obj.attribute1;
}

void set_attr2(Something &obj, const std::string &value)
{
    obj.attribute2 = value;
};
然后,我有一个文件,其中包含一组应应用于已创建对象的信息。但是,应该应用它的属性名也存储在文件中。换句话说,文本文件将包含如下两个值:

123, "attribute1"
我需要一种通过字符串引用对象属性的方法。像
Something[variable\u holding\u attribute\u name]
这样的东西就完美了


在C++中有什么方法可以做到这一点吗?还请注意,我不能使用
map
,因为对象包含多个数据类型。

仅仅因为您的
struct
使用不同的数据类型并不意味着您不能使用
std::map
访问它们,因为您可以。试着这样做:

struct Something
{
    int attribute1;
    string attribute2;
}
struct Something
{
    int attribute1;
    std::string attribute2;
};

void set_attr1(Something &obj, const std::string &value)
{
    std::istringstream iss(value);
    iss >> obj.attribute1;
}

void set_attr2(Something &obj, const std::string &value)
{
    obj.attribute2 = value;
};

struct某物
{
int属性1;
std::字符串属性2;
};
std::map m;
m[“attribute1”]=&set\u成员
//您可以将set_member()用于::attribute2,但是
//std::istringstream将在空白处拆分输入值,
//这可能是不可取的。如果你想保存整个
//值,改为使用set_str_member()。。
m[“attribute2”]=&set\u str\u成员;
...
obj;
标准::字符串值=…;//"123"
std::string name=…;//“属性1”
m[名称](对象,值);
/*
或更安全:
std::map::iterator iter=m.find(名称);
if(iter!=m.end())
iter->second(目标、价值);
*/

在今天C++中没有反射式的本地支持。也许我误解了您的要求,但不会有什么帮助吗?您可以创建一个<代码> STD::MAP< /Calp>(或类似)来查找一段代码来设置与特定名称相关联的字段。不过,您确实需要手动构建和维护映射。@JerryCoffin:由于每个映射都是如此自定义的,所以最好将其作为模板函数:
template membertype&get_mem_by_name(classtype*parent,const char*name)并允许其专用化/重载。您可以使用映射。映射会将一个名称映射到包含字符串的内容。可能更干净(肯定更快)的方法是只调用
stoi
,而不是
istringstream
。除非在读取设置文件时确实需要应用区域设置。如果您使用的是C++11或更高版本,您可以这样做,并且不要介意
stoi()
在转换失败时引发异常。
strol
(和
C_str
)是一个很好的选择,如果您真的想忽略错误。
struct Something
{
    int attribute1;
    std::string attribute2;
};

std::map<std::string, set_func_hlpr<Something>::func_type > m;
m["attribute1"] = &set_member<Something, int, &Something::attribute1>
// you can use set_member() for Something::attribute2, but
// std::istringstream will split the input value on whitespace,
// which may not be desirable. If you want to preserve the whole
// value, use set_str_member() instead..
m["attribute2"] = &set_str_member<Something, &Something::attribute2>;

...

Something obj;

std::string value = ...; // "123"
std::string name = ...; // "attribute1"

m[name](obj, value);
/*
Or safer:
std::map<std::string, set_func>::iterator iter = m.find(name);
if (iter != m.end())
    iter->second(obj, value);
*/