gpt4 book ai didi

c++ - 在 C++ 中,是否有通过字符串调用对象属性的方法?

转载 作者:行者123 更新时间:2023-11-30 05:48:56 29 4
gpt4 key购买 nike

假设我有一个这样定义的对象:

struct Something
{
int attribute1;
string attribute2;
}

然后我有一个文件,其中包含应应用于已创建对象的一堆信息。但是,它应该应用的属性名称也存储在文件中。换句话说,文本文件将包含两个值,如下所示:

123, "attribute1"

我需要一种通过字符串引用对象属性的方法。像 Something[variable_holding_attribute_name] 这样的东西会很完美!

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

最佳答案

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

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;
};

typedef void (*set_func)(Something&, const std::string&);

std::map<std::string, set_func> m;
m["attribute1"] = &set_attr1;
m["attribute2"] = &set_attr2;

...

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);
*/

如果您想要更灵活一点的东西,允许您为相同数据类型的多个字段重复使用给定的函数,甚至可以为 map 重复使用相同的函数。不同的struct s,你可以这样做:

template<typename ObjType, typename MemType, MemType ObjType::*member>
void set_member(ObjType &obj, const std::string &value)
{
std::istringstream iss(value);
iss >> obj.*member;
}

template<typename ObjType, std::string ObjType::*member>
void set_str_member(ObjType &obj, const std::string &value)
{
obj.*member = value;
}

template<typename ObjType>
struct set_member_hlpr
{
typedef void (*func_type)(ObjType&, const std::string&);
};

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);
*/

关于c++ - 在 C++ 中,是否有通过字符串调用对象属性的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27993784/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com