9

考慮下面這個簡單的使用Boost.Program_Options的:Boost.Program_Options:當指定<bool>作爲命令行選項時,什麼是有效的命令行參數?

boost::program_options::options_description options("Options"); 

options.add_options() 

    ("my_bool_flag,b", boost::program_options::value<bool>(), "Sample boolean switch)") 

    ; 

...將評估爲false什麼命令行參數,以及如何true

(即,假設該程序被命名爲「富」,並在命令行上執行: foo -b ? ...問號一些其他的文本佔位符:什麼都是可能的文本選擇,將正確評估爲false,以及如何true

回答

19

縱觀$(BOOST_ROOT)/libs/program_options/src/value_semantic.cpp你可以找到:

/* Validates bool value. 
    Any of "1", "true", "yes", "on" will be converted to "1".<br> 
    Any of "0", "false", "no", "off" will be converted to "0".<br> 
    Case is ignored. The 'xs' vector can either be empty, in which 
    case the value is 'true', or can contain explicit value. 
*/ 
BOOST_PROGRAM_OPTIONS_DECL void validate(any& v, const vector<string>& xs, 
        bool*, int) 
{ 
    check_first_occurrence(v); 
    string s(get_single_string(xs, true)); 

    for (size_t i = 0; i < s.size(); ++i) 
     s[i] = char(tolower(s[i])); 

    if (s.empty() || s == "on" || s == "yes" || s == "1" || s == "true") 
     v = any(true); 
    else if (s == "off" || s == "no" || s == "0" || s == "false") 
     v = any(false); 
    else 
     boost::throw_exception(invalid_bool_value(s)); 
}