Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,14 @@ class Argument {
}
}
if (m_default_value.has_value()) {
if (m_default_value_str.has_value()) {
if (!m_implicit_value.has_value()) {
if (std::holds_alternative<valued_action>(m_action)) {
return std::any_cast<T>(
std::get<valued_action>(m_action)(*m_default_value_str));
}
}
}
return std::any_cast<T>(m_default_value);
}
if constexpr (details::IsContainer<T>) {
Expand Down
38 changes: 37 additions & 1 deletion test/test_default_value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,40 @@ TEST_CASE("Position of the argument with default value") {
REQUIRE(program.get("-g") == std::string("a_different_value"));
REQUIRE(program.get("-s") == std::string("./src"));
}
}
}

TEST_CASE("Custom data type with default value") {
enum class CustomType { Value1, Value2, INVALID };

auto convert_custom_type = [](const std::string &input) -> CustomType {
if (input == "value1") {
return CustomType::Value1;
}
if (input == "value2") {
return CustomType::Value2;
}
return CustomType::INVALID;
};

argparse::ArgumentParser program("test");
program.add_argument("--custom1")
.default_value("value1")
.action(convert_custom_type);
program.add_argument("--custom2")
.default_value("value2")
.action(convert_custom_type);
program.add_argument("--custom3")
.default_value("value3")
.action(convert_custom_type);
program.add_argument("--custom4")
.default_value("value1")
.action(convert_custom_type);

// custom1-3 as their default values, custom4 with given value
REQUIRE_NOTHROW(program.parse_args({"test", "--custom4", "value2"}));

REQUIRE(program.get<CustomType>("custom1") == CustomType::Value1);
REQUIRE(program.get<CustomType>("custom2") == CustomType::Value2);
REQUIRE(program.get<CustomType>("custom3") == CustomType::INVALID);
REQUIRE(program.get<CustomType>("custom4") == CustomType::Value2);
}