2012-05-30 25 views
1

我已經實現了一個使用具有硬編碼屬性的類的算法。C++從配置文件構建類屬性

但現在,我想爲它增加一些靈活性。

假設我只使用了四個可用於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元素的持續時間值。

這可能嗎?我該怎麼做?

+1

據我所知'operator'是C++中的保留關鍵字,也許你應該用一個又一個。 – Constantinius

+0

你的意思是什麼*「聲音應該只用這三個屬性來建立」*? – Constantinius

+0

@Constantinius:你說的對,我只是把它作爲一個例子,我會改變它的。 – Luis

回答

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