diff --git a/CHANGELOG.md b/CHANGELOG.md index ae743867..7b8d79c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * Ini output now includes `=false` when `default_also` is true * Ini no longer lists the help pointer * Added test for inclusion in multiple files and linking, fixed issues (rarely needed for CLI, but nice for tools) +* Support for complex numbers ## Version 0.8 diff --git a/README.md b/README.md index d02dbbad..386dd788 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,8 @@ app.add_options(option_name, help_string="", default=false) +app.add_complex(... // Special case: support for complex numbers + app.add_flag(option_name, int_or_bool = nothing, help_string="") diff --git a/include/CLI/App.hpp b/include/CLI/App.hpp index 4fbf96e8..32181e47 100644 --- a/include/CLI/App.hpp +++ b/include/CLI/App.hpp @@ -399,6 +399,33 @@ public: return opt; } + /// Add a complex number + template + Option* add_complex( + std::string name, T& variable, + std::string description="", bool defaulted=false, + std::string label="COMPLEX") { + CLI::callback_t fun = [&variable](results_t res){ + if(res.size()!=2) + return false; + double x,y; + bool worked = detail::lexical_cast(res[0], x) + && detail::lexical_cast(res[1], y); + if(worked) + variable = T(x,y); + return worked; + }; + + CLI::Option* opt = add_option(name, fun, description, defaulted); + opt->set_custom_option(label, 2); + if(defaulted) { + std::stringstream out; + out << variable; + opt->set_default_val(out.str()); + } + return opt; + } + /// Add a configuration ini file option Option* add_config(std::string name="--config", diff --git a/tests/NewParseTest.cpp b/tests/NewParseTest.cpp index 5171de93..fb354793 100644 --- a/tests/NewParseTest.cpp +++ b/tests/NewParseTest.cpp @@ -58,3 +58,34 @@ TEST_F(TApp, DefaultComplex) { EXPECT_EQ(cx(4,3), comp); } + +TEST_F(TApp, BuiltinComplex) { + cx comp {1, 2}; + app.add_complex("-c,--complex", comp, "", true); + + args = {"-c", "4", "3"}; + + std::string help = app.help(); + EXPECT_THAT(help, HasSubstr("1")); + EXPECT_THAT(help, HasSubstr("2")); + EXPECT_THAT(help, HasSubstr("COMPLEX")); + + EXPECT_EQ(cx(1,2), comp); + + run(); + + EXPECT_EQ(cx(4,3), comp); + +} + + +TEST_F(TApp, BuiltinComplexIgnoreI) { + cx comp {1, 2}; + app.add_complex("-c,--complex", comp); + + args = {"-c", "4", "3i"}; + + run(); + + EXPECT_EQ(cx(4,3), comp); +}