Skip to content

Commit

Permalink
Add support for std::optional
Browse files Browse the repository at this point in the history
  • Loading branch information
sjoubert committed Mar 5, 2024
1 parent 2b8bac6 commit 51dc4b4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
20 changes: 20 additions & 0 deletions include/boost/program_options/detail/value_semantic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

#include <boost/throw_exception.hpp>

#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
# include <optional>
#endif

// forward declaration
namespace boost { template<class T> class optional; }

Expand Down Expand Up @@ -169,6 +173,22 @@ namespace boost { namespace program_options {
v = boost::any(boost::optional<T>(boost::any_cast<T>(a)));
}

#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
/** Validates std::optional arguments. */
template<class T, class charT>
void validate(boost::any& v,
const std::vector<std::basic_string<charT> >& s,
std::optional<T>*,
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<T>(boost::any_cast<T>(a)));
}
#endif

template<class T, class charT>
void
typed_value<T, charT>::
Expand Down
11 changes: 9 additions & 2 deletions test/optional_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ namespace po = boost::program_options;

#include <boost/optional.hpp>

#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
# include <optional>
#endif
#include <string>

#include "minitest.hpp"
Expand All @@ -19,9 +22,10 @@ std::vector<std::string> sv(const char* array[], unsigned size)
return r;
}

template<template<typename> class OptionalType>
void test_optional()
{
boost::optional<int> foo, bar, baz;
OptionalType<int> foo, bar, baz;

po::options_description desc;
desc.add_options()
Expand All @@ -48,6 +52,9 @@ void test_optional()

int main(int, char*[])
{
test_optional();
test_optional<boost::optional>();
#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
test_optional<std::optional>();
#endif
return 0;
}

0 comments on commit 51dc4b4

Please sign in to comment.