Add support for std::optional (#132)

This commit is contained in:
Sylvain Joubert
2024-03-05 21:57:52 +01:00
committed by GitHub
parent 2b8bac66a9
commit fafcca13d8
2 changed files with 29 additions and 2 deletions

View File

@@ -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; }
@@ -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>::

View File

@@ -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"
@@ -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()
@@ -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;
}