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.
CString没有任何运算符<<考虑使用std :: string
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.