c++ - lexical_cast<T>(std::string) 的替代方案

标签 c++ templates boost lexical-cast

我有使用 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,_Traits> &std::operator >>(std::basic_istream<_Elem,_Traits> &&,_Elem *)' :无法推导出 'std::basic_istream 的模板参数<_Elem,_Traits> &&' 来自 'std::ostringstream'

最佳答案

lexical_cast使用双向流,<<>> 。您也可以这样做:

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

但请务必包括健全性检查。

关于c++ - lexical_cast<T>(std::string) 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888975/

相关文章:

c++ - DXGI 文本输出轨迹

带有模板编译错误的 C++ 类

C++ 微软 : How to associate uuid/guid with template specialization

c++ - 这篇 cppreference.com 文章的结尾有问题

c++ - 避免使用模板函数的 if-else 语句

c++ - 使用 CMake 编译具有多配置的 Boost

c++ - 如何将 Boost 库添加到 RPI2 上的 QTCreator?

c++ - WSARecv 一次可以接收的最大字节数是多少?

c++登录系统 - 如何返回用户名?

c++ - astar_search 在以 listS 作为顶点容器的图上?