ソースを参照

Add a no-args query option.

Sam Jaffe 5 年 前
コミット
f0db74df84
2 ファイル変更27 行追加0 行削除
  1. 18 0
      include/cli/cli.h
  2. 9 0
      test/cli_test.cxx

+ 18 - 0
include/cli/cli.h

@@ -41,6 +41,12 @@ public:
   cli & register_callback(std::string const & handle, F && cb) {
     return register_callback(handle, lambdas::FFL(cb));
   }
+  template <typename T>
+  cli & register_query(std::string const & handle, std::function<T()> cb);
+  template <typename F>
+  cli & register_query(std::string const & handle, F && cb) {
+    return register_query(handle, lambdas::FFL(cb));
+  }
   
   void run() const;
   template <typename T, size_t I>
@@ -77,4 +83,16 @@ cli & cli::register_callback(std::string const & handle,
   return *this;
 }
 
+template <typename T> void cli_print(T const & value) { std::cout << value; }
+
+template <typename T>
+cli & cli::register_query(std::string const & handle, std::function<T()> cb) {
+  arguments_.emplace(handle, 0);
+  callbacks_.emplace(handle, [=](args_t const & args) {
+    using ::cli::cli_print;
+    cli_print(cb());
+  });
+  return *this;
+}
+
 }

+ 9 - 0
test/cli_test.cxx

@@ -40,3 +40,12 @@ TEST(CliTest, WillSkipCallbackIfNotEnoughArgs) {
   cli::cli(input).register_callback("act", [&](int){ was_hit = true; }).run();
   EXPECT_FALSE(was_hit);
 }
+
+struct example {};
+void cli_print(example const &) { throw example{}; }
+
+TEST(CliTest, QueryInvokesADLFunction) {
+  std::stringstream input{R"(query)"};
+  auto func = [](){ return example{}; };
+  EXPECT_THROW(cli::cli(input).register_query("query", func).run(), example);
+}