Skip to content

Commit

Permalink
Fix ordering of parse_value functions
Browse files Browse the repository at this point in the history
Fixes #419. Put the definitions of parse_value functions before they
are called so that the right ones are chosen.
  • Loading branch information
jarro2783 committed Feb 20, 2024
1 parent 3bf2684 commit 642bdfc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 24 deletions.
44 changes: 22 additions & 22 deletions include/cxxopts.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1062,6 +1062,28 @@ parse_value(const std::string& text, T& value) {
stringstream_parser(text, value);
}

#ifdef CXXOPTS_HAS_OPTIONAL
template <typename T>
void
parse_value(const std::string& text, std::optional<T>& 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<exceptions::incorrect_argument_type>(text);
}

c = text[0];
}

template <typename T>
void
parse_value(const std::string& text, std::vector<T>& value)
Expand Down Expand Up @@ -1097,28 +1119,6 @@ add_value(const std::string& text, std::vector<T>& value)
value.emplace_back(std::move(v));
}

#ifdef CXXOPTS_HAS_OPTIONAL
template <typename T>
void
parse_value(const std::string& text, std::optional<T>& 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<exceptions::incorrect_argument_type>(text);
}

c = text[0];
}

template <typename T>
struct type_is_container
{
Expand Down
8 changes: 6 additions & 2 deletions test/options.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -709,11 +709,13 @@ TEST_CASE("std::vector", "[vector]") {
#ifdef CXXOPTS_HAS_OPTIONAL
TEST_CASE("std::optional", "[optional]") {
std::optional<std::string> optional;
std::optional<bool> opt_bool;
cxxopts::Options options("optional", " - tests optional");
options.add_options()
("optional", "an optional option", cxxopts::value<std::optional<std::string>>(optional));
("optional", "an optional option", cxxopts::value<std::optional<std::string>>(optional))
("optional_bool", "an boolean optional", cxxopts::value<std::optional<bool>>(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();
Expand All @@ -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

Expand Down

0 comments on commit 642bdfc

Please sign in to comment.