use of string_view in as<T> method (#1187)

Address Issue #881, allowing use of string_view in the as<XX> method on
options.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Philip Top
2025-08-09 07:42:18 -07:00
committed by GitHub
parent bb9bd85e3b
commit dfd3d90078
2 changed files with 38 additions and 2 deletions

View File

@@ -319,7 +319,7 @@ class Option : public OptionBase<Option> {
/// complete Results of parsing
results_t results_{};
/// results after reduction
results_t proc_results_{};
mutable results_t proc_results_{};
/// enumeration for the option state machine
enum class option_state : char {
parsing = 0, //!< The option is currently collecting parsed results
@@ -700,7 +700,9 @@ class Option : public OptionBase<Option> {
} else {
res = reduced_results();
}
retval = detail::lexical_conversion<T, T>(res, output);
// store the results in a stable location if the output is a view
proc_results_ = std::move(res);
retval = detail::lexical_conversion<T, T>(proc_results_, output);
}
if(!retval) {
throw ConversionError(get_name(), results_);

View File

@@ -385,6 +385,40 @@ TEST_CASE_METHOD(TApp, "stringLikeTests", "[optiontype]") {
CHECK("bca" == m_type.m_value);
}
#if CLI11_HAS_FILESYSTEM
#include <string_view>
// test code from https://github.com/CLIUtils/CLI11/issues/881
// https://github.com/Jean1995
TEST_CASE_METHOD(TApp, "AsStringView", "[app]") {
app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"}));
args = {};
run();
auto inputStr = app["--input"]->as<std::string_view>();
CHECK(inputStr == "optA");
args = {"--input", "optC"};
run();
inputStr = app["--input"]->as<std::string_view>();
CHECK(inputStr == "optC");
}
#endif
TEST_CASE_METHOD(TApp, "AsStringRef", "[app]") {
app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"}));
args = {};
run();
const std::string &inputStr = app["--input"]->as<std::string>();
CHECK(inputStr == "optA");
args = {"--input", "optC"};
run();
const std::string &inputStr2 = app["--input"]->as<std::string>();
CHECK(inputStr2 == "optC");
}
TEST_CASE_METHOD(TApp, "VectorExpectedRange", "[optiontype]") {
std::vector<std::string> strvec;