From fafcca13d8f6c35bd7cce12c7a61301329193aaa Mon Sep 17 00:00:00 2001 From: Sylvain Joubert Date: Tue, 5 Mar 2024 21:57:52 +0100 Subject: [PATCH] Add support for std::optional (#132) --- .../program_options/detail/value_semantic.hpp | 20 +++++++++++++++++++ test/optional_test.cpp | 11 ++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/include/boost/program_options/detail/value_semantic.hpp b/include/boost/program_options/detail/value_semantic.hpp index 9531339a34..870ce2fb9e 100644 --- a/include/boost/program_options/detail/value_semantic.hpp +++ b/include/boost/program_options/detail/value_semantic.hpp @@ -8,6 +8,10 @@ #include +#ifndef BOOST_NO_CXX17_HDR_OPTIONAL +# include +#endif + // forward declaration namespace boost { template class optional; } @@ -169,6 +173,22 @@ namespace boost { namespace program_options { v = boost::any(boost::optional(boost::any_cast(a))); } +#ifndef BOOST_NO_CXX17_HDR_OPTIONAL + /** Validates std::optional arguments. */ + template + void validate(boost::any& v, + const std::vector >& s, + std::optional*, + int) + { + validators::check_first_occurrence(v); + validators::get_single_string(s); + boost::any a; + validate(a, s, (T*)0, 0); + v = boost::any(std::optional(boost::any_cast(a))); + } +#endif + template void typed_value:: diff --git a/test/optional_test.cpp b/test/optional_test.cpp index b38308e588..cd34ba6e7a 100644 --- a/test/optional_test.cpp +++ b/test/optional_test.cpp @@ -7,6 +7,9 @@ namespace po = boost::program_options; #include +#ifndef BOOST_NO_CXX17_HDR_OPTIONAL +# include +#endif #include #include "minitest.hpp" @@ -19,9 +22,10 @@ std::vector sv(const char* array[], unsigned size) return r; } +template class OptionalType> void test_optional() { - boost::optional foo, bar, baz; + OptionalType foo, bar, baz; po::options_description desc; desc.add_options() @@ -48,6 +52,9 @@ void test_optional() int main(int, char*[]) { - test_optional(); + test_optional(); +#ifndef BOOST_NO_CXX17_HDR_OPTIONAL + test_optional(); +#endif return 0; }