【问题标题】:C++ boost lexical_cast with template?C++ 用模板提升 lexical_cast?
【发布时间】:2011-06-17 21:05:36
【问题描述】:

我正在尝试构建一个将程序设置存储为 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,错误输出很长,我不确定它有什么问题。

【问题讨论】:

    标签: c++ templates boost mfc lexical-cast


    【解决方案1】:

    CString 没有任何操作符

    【讨论】:

    • 或为 CString 提供这样的运算符,因为 lexical_cast 在内部使用 ostringstream 来生成其输出。
    【解决方案2】:

    binary '>>' : 没有找到哪个运算符 接受类型的左操作数 'std::basic_istream<_elem>'

    lexical_cast 基本上尝试将对象写入流对象。

    您需要定义 >> 运算符来写入您正在使用的类中的流以使其工作。 (取决于你是阅读还是写作)

    【讨论】:

      【解决方案3】:

      documentation 中所示,boost::lexical_cast 基于几个事物的存在进行转换。源类型必须有一个接受 std::ostream(或 std::wostream)的 operator>。这些函数的第一个参数是对流的非常量引用,第二个参数是对要发送/构造的类型的引用。

      为了将设置名称转换为 T,该 T 必须具有接受输入流的运算符>>。同样,为了转换为 CString,必须有一个 operator

      【讨论】:

        猜你喜欢
        • 2018-06-01
        • 2011-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        相关资源
        最近更新 更多