Pārlūkot izejas kodu

Automatically print containers.

Sam Jaffe 5 gadi atpakaļ
vecāks
revīzija
6036b976aa
2 mainītis faili ar 29 papildinājumiem un 1 dzēšanām
  1. 27 1
      include/cli/cli.h
  2. 2 0
      test/cli_test.cxx

+ 27 - 1
include/cli/cli.h

@@ -19,6 +19,23 @@
 
 namespace cli {
 
+template <typename T> struct is_string : std::false_type {};
+template <typename T>
+struct is_string<T*> : std::is_same<std::remove_cv_t<T>, char> {};
+template <typename T>
+struct is_string<T[]> : std::is_same<std::remove_cv_t<T>, char> {};
+template <typename...Ts>
+struct is_string<std::basic_string<Ts...>> : std::true_type {};
+
+template <typename T, typename = void> struct is_container : std::false_type {};
+template <typename T>
+struct is_container<T, std::enable_if_t<!std::is_void_v<typename T::value_type>>> : std::true_type {};
+
+template <typename T>
+static constexpr bool const is_string_v = is_string<T>::value;
+template <typename T>
+static constexpr bool const is_container_v = is_container<T>::value;
+
 class cli {
 public:
   using args_t = std::vector<std::string>;
@@ -83,7 +100,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> void cli_print(T const & value) {
+  if constexpr (is_container_v<T> && !is_string_v<T>) {
+    using ::cli::cli_print;
+    for (auto & elem : value) {
+      cli_print(elem);
+    }
+  } else {
+    std::cout << "  " << value << "\n";
+  }
+}
 
 template <typename T>
 cli & cli::register_query(std::string const & handle, std::function<T()> cb) {

+ 2 - 0
test/cli_test.cxx

@@ -16,6 +16,8 @@
 // unit tests.
 #undef EXPECT_THAT
 #define EXPECT_THAT ASSERT_THAT
+#undef EXPECT_THROW
+#define EXPECT_THROW ASSERT_THROW
 #undef EXPECT_TRUE
 #define EXPECT_TRUE ASSERT_TRUE
 #undef EXPECT_FALSE