Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions include/boost/program_options/variables_map.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#include <boost/any.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>

#include <string>
#include <map>
Expand Down Expand Up @@ -74,6 +75,16 @@ namespace boost { namespace program_options {
return boost::any_cast<T&>(v);
}

/** If stored value is of type T, returns optional<T> having that value.
If variable is empty, returns optional<T> having the none.
Otherwise, throws boost::bad_any_cast exception. */
template<class T>
optional<T> as_optional() const {
if (empty()) return none;

return as<T>();
}

/// Returns true if no value is stored.
bool empty() const;
/** Returns true if the value was not explicitly
Expand Down
4 changes: 4 additions & 0 deletions test/variable_map_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ void test_variable_map()
BOOST_CHECK(vm.count("biz") == 1);
BOOST_CHECK(vm["biz"].as<string>() == "3");
BOOST_CHECK(vm["output"].as<string>() == "foo");
BOOST_CHECK(vm["bar"].as_optional<string>() == optional<string>("11"));
BOOST_CHECK(vm["buz"].as_optional<string>() == none);

int i;
desc.add_options()
Expand All @@ -71,6 +73,8 @@ void test_variable_map()
BOOST_CHECK(vm2["zak"].as<int>() == 13);
BOOST_CHECK(vm2["opt"].as<bool>() == false);
BOOST_CHECK(i == 13);
BOOST_CHECK(vm2["zak"].as_optional<int>() == optional<int>(13));
BOOST_CHECK(vm2["zoo"].as_optional<int>() == none);

options_description desc2;
desc2.add_options()
Expand Down