gpt4 book ai didi

c++ - boost::program_options "polymorphic"参数

转载 作者:可可西里 更新时间:2023-11-01 18:36:10 25 4
gpt4 key购买 nike

我想使用 boost::program_options 创建一个可以按如下方式调用的可执行文件:

./example --nmax=0,10  # nmax is chosen randomly between 0 and 10
./example --nmax=9 # nmax is set to 9
./example # nmax is set to the default value of 10

用最少的代码以类型安全的方式实现这一目标的最佳方法是什么?

最佳答案

I would like to use boost::program_options to create an executable which can be called as follows:

program_options 库非常灵活,可以通过使用流插入和提取运算符编写您自己的类轻松支持这一点。

#include <iostream>
#include <limits>
#include <stdlib.h>

#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>


class Max
{
public:
Max() :
_max( std::numeric_limits<int>::max() )
{

}

Max(
int max
) :
_max( max )
{

}

Max(
int low,
int high
)
{
int value = rand();
value %= (high - low);
value += low;
_max = value;
}

int value() const { return _max; }

private:
int _max;
};

std::ostream&
operator<<(
std::ostream& os,
const Max& foo
)
{
os << foo.value();
return os;
}

std::istream&
operator>>(
std::istream& is,
Max& foo
)
{
std::string line;
std::getline( is, line );
if ( !is ) return is;

const std::string::size_type comma = line.find_first_of( ',' );
try {
if ( comma != std::string::npos ) {
const int low = boost::lexical_cast<int>( line.substr(0, comma) );
const int high = boost::lexical_cast<int>( line.substr(comma + 1) );
foo = Max( low, high );
} else {
foo = Max( boost::lexical_cast<int>(line) );
}
} catch ( const boost::bad_lexical_cast& e ) {
std::cerr << "garbage when convering Max value '" << line << "'" << std::endl;

is.setstate( std::ios::failbit );
}

return is;
}

int
main( int argc, char** argv )
{
namespace po = boost::program_options;

Max nmax;

po::options_description options;
options.add_options()
("nmax", po::value(&nmax)->default_value(10), "random number range, or value" )
("help,h", po::bool_switch(), "help text")
;

po::variables_map vm;
try {
po::command_line_parser cmd_line( argc, argv );
cmd_line.options( options );
po::store( cmd_line.run(), vm );
po::notify( vm );
} catch ( const boost::program_options::error& e ) {
std::cerr << e.what() << std::endl;
exit( EXIT_FAILURE );
}

if ( vm["help"].as<bool>() ) {
std::cout << argv[0] << " [OPTIONS]" << std::endl;
std::cout << std::endl;
std::cout << "OPTIONS:" << std::endl;
std::cout << options << std::endl;
exit(EXIT_SUCCESS);
}

std::cout << "random value: " << nmax.value() << std::endl;
}

示例 session

samm:stackoverflow samm$ ./a.out
random value: 10
samm:stackoverflow samm$ ./a.out --nmax 55
random value: 55
samm:stackoverflow samm$ ./a.out --nmax 10,25
random value: 17
samm:stackoverflow samm$

关于c++ - boost::program_options "polymorphic"参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10176053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com