From 5e6d1e29f7546d9d94fe3d193b788b280bf1f37d Mon Sep 17 00:00:00 2001 From: Victor Proon Date: Fri, 18 Jul 2025 00:09:03 +0300 Subject: [PATCH] fix the issue with default empty vectors behaviour. update unit test (#460) --- include/cxxopts.hpp | 9 +++------ test/options.cpp | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 32c8f2c..b9c7407 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1100,22 +1100,19 @@ void parse_value(const std::string& text, char& c) c = text[0]; } +template void add_value(const std::string& text, std::vector& value); + template void parse_value(const std::string& text, std::vector& value) { if (text.empty()) { - T v; - parse_value(text, v); - value.emplace_back(std::move(v)); return; } std::stringstream in(text); std::string token; while(!in.eof() && std::getline(in, token, CXXOPTS_VECTOR_DELIMITER)) { - T v; - parse_value(token, v); - value.emplace_back(std::move(v)); + add_value(token, value); } } diff --git a/test/options.cpp b/test/options.cpp index 843f4ae..6df4972 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -709,6 +709,40 @@ TEST_CASE("std::vector", "[vector]") { CHECK(vector[3] == 4.5); } +TEST_CASE("empty std::vector", "[vector]") { + std::vector double_vector; + std::vector string_vector; + + cxxopts::Options options("empty vector", " - tests behaviour of empty vector options"); + + SECTION("string vector") { + options.add_options() + ("string_vector", "vector of strings", cxxopts::value(string_vector)->default_value("")); + + Argv av({"empty vector"}); + auto** argv = av.argv(); + auto argc = av.argc(); + + options.parse(argc, argv); + + CHECK(string_vector.empty()); + } + + SECTION("double vector") { + options.add_options() + ("double_vector", "vector of doubles", cxxopts::value(double_vector)->default_value("")); + + Argv av({"empty vector"}); + auto** argv = av.argv(); + auto argc = av.argc(); + + options.parse(argc, argv); // throws + + CHECK(double_vector.empty()); + } + +} + #ifdef CXXOPTS_HAS_OPTIONAL TEST_CASE("std::optional", "[optional]") { std::optional optional;