jarro2783 / cxxopts

Lightweight C++ command line option parser

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

use correct type to set default value

ldeng-ustc opened this issue · comments

Is there a way to set default value by correct type instead of string?
In some cases, it increase the readability:

// Hard to read
options.add_options()
    ("t,duration", "Duration in seconds", cxxopts::value<int>()->default_value("86400"));

// Easy to read, but failed to compile.
options.add_options()
    ("t,duration", "Duration in seconds", cxxopts::value<int>()->default_value(24*60*60));

In other cases, default values are calculated from complex constant expressions:

constexpr int f(int n) {
    // do some thing
}

// Failed, f(10) is not string
options.add_options()
    ("t,duration", "Duration in seconds", cxxopts::value<int>()->default_value(f(10)));

I know the difficulty is default_value is virtual and could not be template, which was mentioned in #55. But is it possible to store default/implicit value in std::any?

Sorry for my bad English.

Maybe adding a overload OptionValue::as<T>(T default_value) is a easier way. (But it will be confused that default values are set twice. )

@ldeng-ustc

It is possible with some refactoring
https://github.com/artpaul/cxxopts/blob/default_value/include/cxxopts.hpp#L486
https://github.com/artpaul/cxxopts/blob/default_value/test/options.cpp#L697
but in my implementation, it is lead to break the backward compatibility.

So, maybe the easiest way is to use std::to_string

options.add_options()
    ("t,duration", "Duration in seconds", cxxopts::value<int>()->default_value(std::to_string(24*60*60)));

Thank you, to_string is enough for me.