限制boost :: options_description中std :: cout默认值的精度

Chr*_*ian 10 c++ precision cout boost-program-options

当我构造一个boost :: options_description实例时

options.add_options()
  ("double_val", value(&config.my_double)->default_value(0.2), "it's a double");
Run Code Online (Sandbox Code Playgroud)

然后想要自动输出我的程序可用的选项,然后放

std::cout << options << std::endl;
Run Code Online (Sandbox Code Playgroud)

默认值0.2显示的精度太高,当我有长变量名时,这有效地混淆了我的输出:

--double_val (=0.20000000000000001) it's a double
Run Code Online (Sandbox Code Playgroud)

不幸的是,先前调用std :: cout.precision没有帮助:

cout.precision(5);
std::cout << options << std::endl;
Run Code Online (Sandbox Code Playgroud)

这仍然导致相同的输出:/

您对如何将默认值的显示限制在较少的位置有任何想法吗?

最诚挚的问候,基督

Joh*_*nck 11

来自boost/program_options/value_semantic.hpp:

    /** Specifies default value, which will be used
        if none is explicitly specified. The type 'T' should
        provide operator<< for ostream.
    */
    typed_value* default_value(const T& v)
    {
        m_default_value = boost::any(v);
        m_default_value_as_text = boost::lexical_cast<std::string>(v);
        return this;
    }

    /** Specifies default value, which will be used
        if none is explicitly specified. Unlike the above overload,
        the type 'T' need not provide operator<< for ostream,
        but textual representation of default value must be provided
        by the user.
    */
    typed_value* default_value(const T& v, const std::string& textual)
    {
        m_default_value = boost::any(v);
        m_default_value_as_text = textual;
        return this;
    }
Run Code Online (Sandbox Code Playgroud)

所以实现很简单(Boost永远都不确定!).尝试重新配置你的ostream以使格式化出来你想要的不起作用,因为默认值只是转换为独立ostringstream(内部lexical_cast)的字符串.

因此,一个简单的解决方法是将您想要的字符串表示添加为第二个参数default_value.然后,您可以根据需要进行打印(如果传递空字符串,则根本不打印).像这样:

value(&config.my_double)->default_value(0.2, "0.2")
Run Code Online (Sandbox Code Playgroud)

完成同样事情的更"企业化"的方法是实现你自己的类型,它将包装double,用于config.my_double,并提供构造和强制double,并且你自己ostream& operator<<完全符合你想要的格式.但是,除非你正在编写一个需要通用性的库,否则我不会建议这种方法.

来自Boost Lexical Cast笔记:

先前版本的lexical_cast使用默认流精度来读取和写入浮点数.对于具有相应std :: numeric_limits特化的数字,当前版本现在选择要匹配的精度.