簡體   English   中英

C ++用模板增強lexical_cast嗎?

[英]C++ boost lexical_cast with template?

我正在嘗試建立一個將程序設置存儲為std :: map的類。 由於所有程序設置都存儲為字符串,因此我需要一個訪問器方法,該方法可以將轉換為相關類型的程序設置返回。 我是C ++模板的新手,這是我的第一次嘗試:

class Settings
{
public:
    Settings(void);
    virtual ~Settings(void);

    enum SettingName {HomePageUrl, WindowWidth};

    template<class T>
    T Get(SettingName name)
    {
        return boost::lexical_cast<T>(settings_[name]);
    }

    template<class T>
    void Set(SettingName name, T value)
    {
        settings_[name] = boost::lexical_cast<CString>(value);
    }

private:
    std::map<SettingName, CString> settings_;

};  

但是,出現編譯器錯誤:

...boost\boost_1_46_1\boost\lexical_cast.hpp(776): error C2678: binary '>>' :
no operator found which takes a left-hand operand of type
'std::basic_istream<_Elem,_Traits>' (or there is no acceptable conversion)

..settings.h(33) : see reference to function template instantiation
'Target boost::lexical_cast<CString,T>(const Source &)' being compiled

使用boost時,錯誤輸出會很長,我不確定它出了什么問題。

CString沒有任何運算符<<考慮使用std :: string

二進制'>>':未找到采用'std :: basic_istream <_Elem,_Traits>'類型的左操作數的運算符

lexical_cast基本上嘗試將對象寫入流對象。

您需要定義<<>>運算符,以將其寫入要使用的類中的流以使其正常工作。 (取決於您正在閱讀還是寫作)

文檔中所示,boost :: lexical_cast基於存在的幾種東西進行轉換。 源類型必須具有帶std :: ostream(或std :: wostream)的operator <<,目標類型必須具有帶std :: istream(或std :: wistream)的operator >>。 這些函數的第一個參數是對流的非常量引用,第二個參數是對要發送/構造的類型的引用。

為了將設置名稱轉換為T,該T必須具有采用輸入流的操作符>>。 同樣,為了轉換為CString,必須有一個使用輸出流的operator <<。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM