Skip to content

Commit fafcca1

Browse files
authored
Add support for std::optional (#132)
1 parent 2b8bac6 commit fafcca1

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

include/boost/program_options/detail/value_semantic.hpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88

99
#include <boost/throw_exception.hpp>
1010

11+
#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
12+
# include <optional>
13+
#endif
14+
1115
// forward declaration
1216
namespace boost { template<class T> class optional; }
1317

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

176+
#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
177+
/** Validates std::optional arguments. */
178+
template<class T, class charT>
179+
void validate(boost::any& v,
180+
const std::vector<std::basic_string<charT> >& s,
181+
std::optional<T>*,
182+
int)
183+
{
184+
validators::check_first_occurrence(v);
185+
validators::get_single_string(s);
186+
boost::any a;
187+
validate(a, s, (T*)0, 0);
188+
v = boost::any(std::optional<T>(boost::any_cast<T>(a)));
189+
}
190+
#endif
191+
172192
template<class T, class charT>
173193
void
174194
typed_value<T, charT>::

test/optional_test.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ namespace po = boost::program_options;
77

88
#include <boost/optional.hpp>
99

10+
#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
11+
# include <optional>
12+
#endif
1013
#include <string>
1114

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

25+
template<template<typename> class OptionalType>
2226
void test_optional()
2327
{
24-
boost::optional<int> foo, bar, baz;
28+
OptionalType<int> foo, bar, baz;
2529

2630
po::options_description desc;
2731
desc.add_options()
@@ -48,6 +52,9 @@ void test_optional()
4852

4953
int main(int, char*[])
5054
{
51-
test_optional();
55+
test_optional<boost::optional>();
56+
#ifndef BOOST_NO_CXX17_HDR_OPTIONAL
57+
test_optional<std::optional>();
58+
#endif
5259
return 0;
5360
}

0 commit comments

Comments
 (0)