fix an issue where an enumeration with a stream output method would
generate strings that could not be converted back to the original
enumeration value.

Fixes Issue #1258 

recent changes fixed a few issues with the default_val method. The
method used the to_string, which in cases where a user supplied a
streaming operation to enumerations they could not be converted back to
the enumeration properly resulting in some errors and confusing help
output.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Philip Top
2025-11-29 05:49:47 -08:00
committed by GitHub
parent 53608df1bd
commit f10ee369ee
3 changed files with 25 additions and 2 deletions

View File

@@ -358,7 +358,9 @@ class CheckedTransformer : public Validator {
out += detail::generate_map(detail::smart_deref(mapping)) + " OR {";
out += detail::join(
detail::smart_deref(mapping),
[](const iteration_type_t &v) { return detail::to_string(detail::pair_adaptor<element_t>::second(v)); },
[](const iteration_type_t &v) {
return detail::value_string(detail::pair_adaptor<element_t>::second(v));
},
",");
out.push_back('}');
return out;

View File

@@ -815,7 +815,7 @@ class Option : public OptionBase<Option> {
/// Set the default value and validate the results and run the callback if appropriate to set the value into the
/// bound value only available for types that can be converted to a string
template <typename X> Option *default_val(const X &val) {
std::string val_str = detail::to_string(val);
std::string val_str = detail::value_string(val);
auto old_option_state = current_option_state_;
results_t old_results{std::move(results_)};
results_.clear();

View File

@@ -186,6 +186,27 @@ TEST_CASE_METHOD(TApp, "SimpleTransformFn", "[transform]") {
CHECK(1 == value);
}
enum class Color { kRed, kBlue };
// operator<< outputs full enum name (standard practice)
inline std::ostream &operator<<(std::ostream &os, Color c) { return os << (c == Color::kRed ? "kRed" : "kBlue"); }
// test from https://github.com/CLIUtils/CLI11/issues/1258 [huweiATgithub](https://github.com/huweiATgithub)
TEST_CASE_METHOD(TApp, "streamTransformCheck", "[transform]") {
std::map<std::string, Color> color_map = {
{"red", Color::kRed}, // User types "red"
{"blue", Color::kBlue} // User types "blue"
};
Color color = Color::kRed;
app.add_option("--color", color)
->transform(CLI::CheckedTransformer(color_map, CLI::ignore_case))
->default_val(Color::kRed); // BUG: Validates "kRed" against {"red", "blue"}
CHECK_NOTHROW(app.parse("")); // Should use default
}
#if defined(CLI11_HAS_STRING_VIEW)
TEST_CASE_METHOD(TApp, "StringViewTransformFn", "[transform]") {
std::string value;