boost::lexical_cast方便,但性能不如std::from_chars和std::to_chars,也不能方便的转换非十进制数。
boost::convert可以做以上转换,而且返回值为boost::optional,一些情况下比处理异常清晰
但是用户自定义类型到std::string的转换fmt库也很方便,boost::convert的方便在于字符串到用户自定义类型的转换,或者直接用工厂模式更好些?
#include <boost/lexical_cast.hpp> #include <catch2/catch.hpp> TEST_CASE("lexical_cast") { REQUIRE(boost::lexical_cast<short>("3") == 3); REQUIRE(boost::lexical_cast<short>("-3") == -3); REQUIRE(boost::lexical_cast<short>("013") == 13); // supports decimal only // "Lexical conversion to any char type is simply reading a byte from source, // since the source has more than one byte, the exception is thrown. REQUIRE_THROWS_AS(boost::lexical_cast<int8_t>("127"), boost::bad_lexical_cast); REQUIRE_THROWS_AS(boost::lexical_cast<unsigned char>("127"), boost::bad_lexical_cast); short d1{}; // d1 is undefined after failed conversion REQUIRE_FALSE(boost::conversion::try_lexical_convert("65536", d1)); short d2{}; // thus another variable is declared here REQUIRE_FALSE(boost::conversion::try_lexical_convert("0xf", d2)); std::array<char, 5> buf; buf = boost::lexical_cast<decltype(buf)>(1234); REQUIRE(strcmp(buf.data(), "1234") == 0); // overrun the buffer REQUIRE_THROWS_AS(boost::lexical_cast<decltype(buf)>(12345), boost::bad_lexical_cast); }