gpt4 book ai didi

c++从配置文件构建类属性

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:25 25 4
gpt4 key购买 nike

我已经使用具有硬编码属性的类实现了一种算法。

但现在,我想给它增加一些灵 active 。

假设我只使用了 class Voice 可用的四个属性中的两个。可用,我的意思是我有他们的数据,存储在数据库中。

class Voice
{
double price; // used this one.
unsigned int duration; // and this one.
string destination;
string operatorid;
}

我创建了一个 vector ,使得 vector [0][0] = 第一个元素的价格, vector [0][1] = 第一个元素的持续时间,依此类推。

我希望用户编辑配置文件(我一直在使用 SimpleIni.h ),并添加他想要的属性,最好按照他想要的顺序添加,例如:

[Voice]
attribute1 = operatorid
attribute2 = price
attribute3 = duration

Voice 应该只用这三个属性构建,这样 vector[n] 就会有 vector[n][0] = operatorid for 的值nth 元素,vector[n][1] = nth 元素的价格值,vector[n][2] = nth 元素的持续时间值。

这可能吗?我该怎么做?

最佳答案

这让我想起了 Python(只是一点点):

#include <string>
#include <map>
#include <iostream>

#include <boost/variant.hpp>
#include <boost/variant/get.hpp>
#include <boost/format.hpp>

class Foo
{
typedef boost::variant<double, int, std::string> var;

struct NoSuchAttributeError {
NoSuchAttributeError(const std::string &key) {
std::cout << boost::format("Attribute %s not found!\n") % key;
}
};

std::map<std::string, var> attributes;

var& getattr(const std::string& key) {
std::map<std::string, var>::iterator it = attributes.find(key);
if (it == attributes.end()) {
throw NoSuchAttributeError(key);
}
else {
return (*it).second;
}
}

template<typename T>
T& get(var& v) {
return boost::get<T, double, int, std::string>(v);
}

public:
Foo() {
// TODO: add attributes according to configuration file
attributes["foo"] = 42;
attributes["bar"] = "baz";
}

// TODO: add appropriate getters/setters for attributes
int& foo() { return get<int>(attributes["foo"]); }
std::string& bar() { return get<std::string>(attributes["bar"]); }
};

int main() {
Foo f;
std::cout << f.foo() << " " << f.bar() << std::endl;
f.foo() = 13;
f.bar() = "Hello World!";
std::cout << f.foo() << " " << f.bar() << std::endl;
return 0;
}

关于c++从配置文件构建类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819139/

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