Boost program options with default values always present when using vm.count()

ぐ巨炮叔叔 提交于 2019-12-06 17:48:19

问题


I've been trying to validate my passed options with boost::program_options. My command has several modes, each of which have associated params that can be specified. What I'm trying to do is ensure these associated params are passed with the mode, i.e.

unicorn --fly --magic-wings-threshold

Where --fly is the mode and --magic-wings-threshold is an associated param. What I've noticed is if --magic-wings-threshold has a default value, e.g.

("magic-wings-threshold,w", po::value<double>(&wings_thresh)->default_value(0.8, "0.8"),
           "Magic wings maximum power"
)

then I can't use

if (vm.count("magic-wings-threshold")( {
    // do stuff
}

to detect if the user passed that param.

It appears that default value params are always passed and detected in vm.count(). Does anyone know a workaround or alternative?


回答1:


use boost::program_options::variable_value::defaulted()

if (vm["magic-wings-threshold"].defaulted())  {
    // assume defaulted value
} else {
    // one was provided
}



回答2:


If you want to tell difference between

-k option not provided
-k provided

You should use po::value()->implicit_value(), You can tell the different situations with:

-k option not provided  ->  vm["k"]==0  
-k option provided      ->  vm["k"]==1


来源:https://stackoverflow.com/questions/9200598/boost-program-options-with-default-values-always-present-when-using-vm-count

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