c++ 从配置文件生成类属性

c++ Build class attributes from configuration file

本文关键字:属性 配置文件 c++      更新时间:2023-10-16

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

但是现在,我想为它增加一些灵活性。

假设我只使用了四个可用于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;
}