Search code examples
c++templatesboostmfclexical-cast

C++ boost lexical_cast with template?


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.


Solution

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