diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 118e2145..d89c0476 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -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(m_action)) { + return std::any_cast( + std::get(m_action)(*m_default_value_str)); + } + } + } return std::any_cast(m_default_value); } if constexpr (details::IsContainer) { diff --git a/test/test_default_value.cpp b/test/test_default_value.cpp index 5287173b..8f01923d 100644 --- a/test/test_default_value.cpp +++ b/test/test_default_value.cpp @@ -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")); } -} \ No newline at end of file +} + +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("custom1") == CustomType::Value1); + REQUIRE(program.get("custom2") == CustomType::Value2); + REQUIRE(program.get("custom3") == CustomType::INVALID); + REQUIRE(program.get("custom4") == CustomType::Value2); +}