From 642bdfc05b7979cb4f56d0b515de9a33dca5ce5f Mon Sep 17 00:00:00 2001 From: Jarryd Beck Date: Tue, 20 Feb 2024 18:45:03 +1100 Subject: [PATCH] Fix ordering of parse_value functions Fixes #419. Put the definitions of parse_value functions before they are called so that the right ones are chosen. --- include/cxxopts.hpp | 44 ++++++++++++++++++++++---------------------- test/options.cpp | 8 ++++++-- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 5bef619c..b5e0d440 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1062,6 +1062,28 @@ parse_value(const std::string& text, T& value) { stringstream_parser(text, value); } +#ifdef CXXOPTS_HAS_OPTIONAL +template +void +parse_value(const std::string& text, std::optional& value) +{ + T result; + parse_value(text, result); + value = std::move(result); +} +#endif + +inline +void parse_value(const std::string& text, char& c) +{ + if (text.length() != 1) + { + throw_or_mimic(text); + } + + c = text[0]; +} + template void parse_value(const std::string& text, std::vector& value) @@ -1097,28 +1119,6 @@ add_value(const std::string& text, std::vector& value) value.emplace_back(std::move(v)); } -#ifdef CXXOPTS_HAS_OPTIONAL -template -void -parse_value(const std::string& text, std::optional& value) -{ - T result; - parse_value(text, result); - value = std::move(result); -} -#endif - -inline -void parse_value(const std::string& text, char& c) -{ - if (text.length() != 1) - { - throw_or_mimic(text); - } - - c = text[0]; -} - template struct type_is_container { diff --git a/test/options.cpp b/test/options.cpp index caad3dd9..24fc7068 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -709,11 +709,13 @@ TEST_CASE("std::vector", "[vector]") { #ifdef CXXOPTS_HAS_OPTIONAL TEST_CASE("std::optional", "[optional]") { std::optional optional; + std::optional opt_bool; cxxopts::Options options("optional", " - tests optional"); options.add_options() - ("optional", "an optional option", cxxopts::value>(optional)); + ("optional", "an optional option", cxxopts::value>(optional)) + ("optional_bool", "an boolean optional", cxxopts::value>(opt_bool)->default_value("false")); - Argv av({"optional", "--optional", "foo"}); + Argv av({"optional", "--optional", "foo", "--optional_bool", "true"}); auto** argv = av.argv(); auto argc = av.argc(); @@ -722,6 +724,8 @@ TEST_CASE("std::optional", "[optional]") { REQUIRE(optional.has_value()); CHECK(*optional == "foo"); + CHECK(opt_bool.has_value()); + CHECK(*opt_bool); } #endif