来自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;
}
所以实现非常简单(Boost 从来都不是确定的事情!)。尝试重新配置您的 ostream 以使格式按照您的意愿出现是行不通的,因为默认值只是被转换为独立ostringstream
(内部lexical_cast
)中的字符串。
因此,一个简单的解决方法是将所需的字符串表示形式作为第二个参数添加到default_value
. 然后你可以让它打印你想要的任何东西(包括根本不打印,如果你传递一个空字符串)。像这样:
value(&config.my_double)->default_value(0.2, "0.2")
完成同样事情的更“企业”的方式是实现您自己的类型,该类型将 wrap double
、用于config.my_double
、并提供构造 from 和强制 to double
,并且您自己ostream& operator<<
的类型完全符合您想要的格式。但是,我不建议使用这种方法,除非您正在编写一个需要通用性的库。
来自 Boost Lexical Cast 笔记:
以前版本的 lexical_cast 使用默认的流精度来读取和写入浮点数。对于具有相应的 std::numeric_limits 特化的数字,当前版本现在选择一个精度来匹配。