2

I'm trying to build a class that stores program settings as a 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:

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.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
User
  • 62,498
  • 72
  • 186
  • 247

3 Answers3

4

CString does not have any operator<< Consider using std::string

Joel Falcou
  • 6,247
  • 1
  • 17
  • 34
3

binary '>>' : no operator found which takes a left-hand operand of type 'std::basic_istream<_Elem,_Traits>'

lexical_cast basically tries to write the object into a stream object.

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)

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
3

As shown in the documentation, boost::lexical_cast does its conversion based on the presence of several things. 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). 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. Similarly, in order to convert to a CString, there must be an operator<< that takes an output stream.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982