Skip to content

Commit dfd3d90

Browse files
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>
1 parent bb9bd85 commit dfd3d90

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

include/CLI/Option.hpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ class Option : public OptionBase<Option> {
319319
/// complete Results of parsing
320320
results_t results_{};
321321
/// results after reduction
322-
results_t proc_results_{};
322+
mutable results_t proc_results_{};
323323
/// enumeration for the option state machine
324324
enum class option_state : char {
325325
parsing = 0, //!< The option is currently collecting parsed results
@@ -700,7 +700,9 @@ class Option : public OptionBase<Option> {
700700
} else {
701701
res = reduced_results();
702702
}
703-
retval = detail::lexical_conversion<T, T>(res, output);
703+
// store the results in a stable location if the output is a view
704+
proc_results_ = std::move(res);
705+
retval = detail::lexical_conversion<T, T>(proc_results_, output);
704706
}
705707
if(!retval) {
706708
throw ConversionError(get_name(), results_);

tests/OptionTypeTest.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,40 @@ TEST_CASE_METHOD(TApp, "stringLikeTests", "[optiontype]") {
385385
CHECK("bca" == m_type.m_value);
386386
}
387387

388+
#if CLI11_HAS_FILESYSTEM
389+
#include <string_view>
390+
// test code from https://github.com/CLIUtils/CLI11/issues/881
391+
// https://github.com/Jean1995
392+
TEST_CASE_METHOD(TApp, "AsStringView", "[app]") {
393+
app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"}));
394+
395+
args = {};
396+
run();
397+
auto inputStr = app["--input"]->as<std::string_view>();
398+
CHECK(inputStr == "optA");
399+
400+
args = {"--input", "optC"};
401+
run();
402+
inputStr = app["--input"]->as<std::string_view>();
403+
CHECK(inputStr == "optC");
404+
}
405+
406+
#endif
407+
408+
TEST_CASE_METHOD(TApp, "AsStringRef", "[app]") {
409+
app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"}));
410+
411+
args = {};
412+
run();
413+
const std::string &inputStr = app["--input"]->as<std::string>();
414+
CHECK(inputStr == "optA");
415+
416+
args = {"--input", "optC"};
417+
run();
418+
const std::string &inputStr2 = app["--input"]->as<std::string>();
419+
CHECK(inputStr2 == "optC");
420+
}
421+
388422
TEST_CASE_METHOD(TApp, "VectorExpectedRange", "[optiontype]") {
389423
std::vector<std::string> strvec;
390424

0 commit comments

Comments
 (0)