简体   繁体   English

C ++用模板增强lexical_cast吗?

[英]C++ boost lexical_cast with template?

I'm trying to build a class that stores program settings as a std::map. 我正在尝试建立一个将程序设置存储为std :: map的类。 Since all the program settings are stored as strings I'd like an accessor method that can return the program setting casted to the relevant type. 由于所有程序设置都存储为字符串,因此我需要一个访问器方法,该方法可以将转换为相关类型的程序设置返回。 I'm new to templating in C++ and this is my first attempt: 我是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_;

};  

However, I'm getting a compiler errors: 但是,出现编译器错误:

...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

With boost the error output is very long and I'm not really sure what's wrong with it. 使用boost时,错误输出会很长,我不确定它出了什么问题。

CString没有任何运算符<<考虑使用std :: string

binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_istream<_Elem,_Traits>' 二进制'>>':未找到采用'std :: basic_istream <_Elem,_Traits>'类型的左操作数的运算符

lexical_cast basically tries to write the object into a stream object. lexical_cast基本上尝试将对象写入流对象。

you need << and >> operator defined to write to a stream in the class you're using for it to work. 您需要定义<<>>运算符,以将其写入要使用的类中的流以使其正常工作。 (depends if you're reading or writing) (取决于您正在阅读还是写作)

As shown in the documentation , boost::lexical_cast does its conversion based on the presence of several things. 文档中所示,boost :: lexical_cast基于存在的几种东西进行转换。 The source type must have an operator<< that takes a std::ostream (or std::wostream), and the destination type must have an operator>> that takes a std::istream (or std::wistream). 源类型必须具有带std :: ostream(或std :: wostream)的operator <<,目标类型必须具有带std :: istream(或std :: wistream)的operator >>。 The first parameter to these function is a non-const reference to the stream, and the second parameter is a reference to the type to send/construct. 这些函数的第一个参数是对流的非常量引用,第二个参数是对要发送/构造的类型的引用。

In order to convert a setting name to a T, that T must have an operator>> that takes an input stream. 为了将设置名称转换为T,该T必须具有采用输入流的操作符>>。 Similarly, in order to convert to a CString, there must be an operator<< that takes an output stream. 同样,为了转换为CString,必须有一个使用输出流的operator <<。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM