1

ハードコーディングされた属性を持つクラスを使用して、アルゴリズムを既に実装しています。

しかし今、私はそれにいくらかの柔軟性を加えたいと思っています。

で使用できる 4 つの属性のうち 2 つだけを使用したとしますclass Voice。利用可能とは、データベースに保存されたデータを持っていることを意味します。

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

vector[0][0] = 最初の要素の価格、vector[0][1] = 最初の要素の期間などのベクトルを作成しました。

ユーザーに構成ファイルを編集してもらいたい(私はSimpleIni.hを使用しています)、必要な属性を追加します。たとえば、次のように、必要な順序で追加してください。

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

Voicevector[n] が、=要素vector[n][0]の operatorid の値、=要素の価格の値、 = 要素の期間の値を持つように、これらの 3 つの属性のみを使用して構築する必要があります。nthvector[n][1]nthvector[n][2]nth

これは可能ですか?どうすればいいですか?

4

1 に答える 1

0

これは私に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;
}
于 2012-05-30T19:42:08.307 に答える