【问题标题】:Alternative to lexical_cast<T>(std::string)lexical_cast<T>(std::string) 的替代方案
【发布时间】:2011-07-31 10:47:59
【问题描述】:

我有使用 lexical_cast 的模板化代码。

现在我想删除所有 lexical_cast 调用(因为它不适用于 /clr)。

我需要在 std::string 和它们的值之间转换对象。

所以,第一个方向很简单(T _from, std::string _to):

std::ostringstream os;
os << _from;
_to =  os.str();

但我想不出一种从字符串到任何类型的通用方法(我需要一些可以与模板一起使用的通用方法,不能只对每种类型使用特化并使用像atoi 这样的函数)

编辑:

当然,我已经尝试在相反的方向使用 ostringstream。我收到此错误:

错误 C2784: 'std::basic_istream<_elem> &std::operator >>(std::basic_istream<_elem> &&,_Elem *)' : 无法推断出 'std::basic_istream 的模板参数<_elem> &&' 来自 'std::ostringstream'

【问题讨论】:

    标签: c++ templates boost lexical-cast


    【解决方案1】:

    lexical_cast 使用双向流,&lt;&lt;&gt;&gt;。你也可以这样做:

    std::stringstream sstr;
    sstr << _from;
    sstr >> _to;
    

    但请务必包含完整性检查。

    【讨论】:

    • 当然试过了...我收到此错误:错误 C2784: 'std::basic_istream<_elem> &std::operator >>(std::basic_istream<_elem> && ,_Elem *)' : 无法从 'std::ostringstream' 中推断出 'std::basic_istream<_elem> &&' 的模板参数
    • @Yochai 您正在尝试使用ostringstream!当然,这只允许输出流,而不是输入流。请改用stringstream
    • 大声笑,没有注意到那里的 o... 看代码太久了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多