Locale invariant guarantee of boost::lexical_cast<>

雨燕双飞 提交于 2019-12-01 17:32:07

Can I force the boost::lexical_cast<> not to be aware of locales?

No, I don't think that is possible. The best you can do is call

std::locale::global(std::locale::classic());

to set the global locale to the "C" locale as boost::lexical_cast relies on the global locale. However, the problem is if somewhere else in the code the global locale is set to something else before calling boost::lexical_cast, then you still have the same problem. Therefore, a robust solution would be imbue a stringstream like so, and you can be always sure that this works:

std::ostringstream oss;
oss.imbue(std::locale::classic());
oss.precision(std::numeric_limits<double>::digits10);
oss << 0.15784465;

A better solution to this problem is to use a boost::locale instead of a std::locale as the globale locale. From the documentation:

Setting the global locale has bad side effects... it affects even printf and libraries like boost::lexical_cast giving incorrect or unexpected formatting. In fact many third-party libraries are broken in such a situation. Unlike the standard localization library, Boost.Locale never changes the basic number formatting, even when it uses std based localization backends, so by default, numbers are always formatted using C-style locale. Localized number formatting requires specific flags.

Boost locale requires you to specify explicitly when you want numeric formatting to be locale aware, which is more consistent with recent library decisions like std::money_put.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!