这个简短的C++程序以一种令我困惑的方式运行:
#include <cassert>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main(void) {
signed char c = -2;
assert(c == -2);
c = boost::lexical_cast<signed char>(std::string("-2"));
std::cout << c << "\n";
}使用g++ 5.2.1和boost-1.58.0,我得到:
在抛出'boost::exception_detail::clone_impl >‘():糟糕的词法转换:源类型值不能解释为目标后调用的终止
为什么不能从字符串"-2“提升到signed char,因为-2值可以用这种类型表示?
发布于 2015-12-20 13:09:09
解决方案是使用Boost:
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
int tmp = boost::lexical_cast<int>(std::string("-2"));
char c = boost::numeric_cast<signed char>(tmp);https://stackoverflow.com/questions/34376293
复制相似问题