From 2fae7e2cdf7486ab17cf754b3e51034722a4b57f Mon Sep 17 00:00:00 2001 From: Henry Fredrick Schreiner Date: Fri, 3 Feb 2017 21:32:58 -0500 Subject: [PATCH] Adding bool flag --- include/CLI.hpp | 34 ++++++++++++++++++++++++++++++++-- tests/CLITest.cpp | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/include/CLI.hpp b/include/CLI.hpp index 1b83c604..b546068d 100644 --- a/include/CLI.hpp +++ b/include/CLI.hpp @@ -104,6 +104,16 @@ struct is_vector > { static bool const value = true; }; +template +struct is_bool { + static const bool value = false; +}; + +template<> +struct is_bool { + static bool const value = true; +}; + namespace detail { // Based generally on https://rmf.io/cxx11/almost-static-if /// Simple empty scoped class @@ -748,10 +758,11 @@ public: } /// Add option for flag - template::value, detail::enabler> = detail::dummy> + template::value && !is_bool::value, detail::enabler> = detail::dummy> Option* add_flag( std::string name, ///< The name, short,long - T &count, ///< A varaible holding the count + T &count, ///< A varaible holding the count std::string discription="" ///< Discription string ) { @@ -764,6 +775,25 @@ public: return add_option(name, fun, discription, NOTHING); } + /// Bool version only allows the flag once + template::value, detail::enabler> = detail::dummy> + Option* add_flag( + std::string name, ///< The name, short,long + T &count, ///< A varaible holding true if passed + std::string discription="" ///< Discription string + ) { + + count = false; + CLI::callback_t fun = [&count](CLI::results_t res){ + count = true; + return res.size() == 1; + }; + + return add_option(name, fun, discription, NOTHING); + } + + /// Add set of options template Option* add_set( diff --git a/tests/CLITest.cpp b/tests/CLITest.cpp index 04364045..ac830fa6 100644 --- a/tests/CLITest.cpp +++ b/tests/CLITest.cpp @@ -141,6 +141,38 @@ TEST_F(TApp, LotsOfFlags) { EXPECT_EQ(1, app.count("A")); } + +TEST_F(TApp, BoolAndIntFlags) { + + bool bflag; + int iflag; + unsigned int uflag; + + app.add_flag("b", bflag); + app.add_flag("i", iflag); + app.add_flag("u", uflag); + + args = {"-b", "-i", "-u"}; + EXPECT_NO_THROW(run()); + EXPECT_TRUE(bflag); + EXPECT_EQ(1, iflag); + EXPECT_EQ((unsigned int) 1, uflag); + + app.reset(); + + args = {"-b", "-b"}; + EXPECT_THROW(run(), CLI::ParseError); + + app.reset(); + bflag = false; + + args = {"-iiiuu"}; + EXPECT_NO_THROW(run()); + EXPECT_FALSE(bflag); + EXPECT_EQ(3, iflag); + EXPECT_EQ((unsigned int) 2, uflag); +} + TEST_F(TApp, ShortOpts) { unsigned long long funnyint;