c++ 从配置文件生成类属性
c++ Build class attributes from configuration file
我已经使用具有硬编码属性的类实现了算法。
但是现在,我想为它增加一些灵活性。
假设我只使用了四个可用于class Voice
的属性中的两个。 通过可用,我的意思是我有他们的数据,存储在数据库中。
class Voice
{
double price; // used this one.
unsigned int duration; // and this one.
string destination;
string operatorid;
}
我创建了一个向量,使得向量 [0][0] = 第一个元素的价格,向量 [0][1] = 第一个元素的持续时间,依此类推。
我希望用户编辑配置文件(我一直在使用 SimpleIni.h),并添加他想要的属性,最好按照他想要的顺序,例如:
[Voice]
attribute1 = operatorid
attribute2 = price
attribute3 = duration
Voice
应该只用这三个属性来构建,以便 vector[n] vector[n][0]
= nth
元素的 operatorid 值,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;
}
相关文章:
- 无法找到/读取配置文件.conf-FileIOException
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 一种在C++中读取TXT配置文件的简单方法
- FFMPEG配置文件级别id大小无效
- 配置文件解析器仅返回以前的值
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- Boost program_options将多个配置文件解析结果存储到一个parsed_options中
- Windows 后台服务(系统配置文件)无法使用 C++ 访问 win 10 上的用户 appData 文件夹?
- 我应该如何获取配置文件的绝对路径与 Windows .exe一起发布?
- 即使使用 FILE_FLAG_DELETE_ON_CLOSE 属性创建文件,文件也会保留在磁盘上
- JPG-如何从ICC配置文件部分APP2读取/提取数据
- My Project的属性配置正确,但Visual Studio仍然无法打开包含头文件
- 检测到 Conan 配置文件设置与 CMake 之间的编译器版本不匹配
- boost::p rogram_options 配置文件格式
- 如何在Boost::program_options配置文件中为非字符串的自定义选项值类型处理空格
- 如何在 Boost Program_Options 中使用命令行和分层配置文件的选项
- 如何将不可编译的配置文件添加到QT工程中?
- OpenGL不能在核心配置文件中使用glVertexAttrib进行绘制
- 如何使用Boost C 属性映射从配置文件中提取值
- c++ 从配置文件生成类属性