1 // accumulator.h: accumulating value for boost program_options.
3 // Copyright (C) 2010, 2011 Free Software Foundation, Inc
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 #ifndef PROGRAM_OPTIONS_ACCUMULATOR_HPP
21 #define PROGRAM_OPTIONS_ACCUMULATOR_HPP
23 #include <boost/program_options/value_semantic.hpp>
24 #include <boost/any.hpp>
25 #include <boost/function.hpp>
29 /// An accumulating option value to handle multiple incrementing options.
31 class accumulator_type
: public boost::program_options::value_semantic
35 accumulator_type() : _interval(1), _default(0) {}
37 /// Set the notifier function.
38 accumulator_type
* notifier(boost::function1
<void, const T
&> f
) {
43 /// Set the default value for this option.
44 accumulator_type
* default_value(const T
& t
) {
49 /// Set the implicit value for this option.
51 /// Unlike for program_options::value, this specifies a value
52 /// to be applied on each occurence of the option.
53 accumulator_type
* implicit_value(const T
& t
) {
58 virtual std::string
name() const { return std::string(); }
60 /// There are no tokens for an accumulator_type
61 virtual unsigned min_tokens() const { return 0; }
62 virtual unsigned max_tokens() const { return 0; }
64 /// Accumulating from different sources is silly.
65 virtual bool is_composing() const { return false; }
67 /// Requiring one or more appearances is unlikely.
68 virtual bool is_required() const { return false; }
70 /// Every appearance of the option simply increments the value
72 /// There should never be any tokens.
73 virtual void parse(boost::any
& value_store
,
74 const std::vector
<std::string
>& new_tokens
,
77 assert(new_tokens
.empty());
78 if (value_store
.empty()) value_store
= T();
79 boost::any_cast
<T
&>(value_store
) += _interval
;
82 /// If the option doesn't appear, this is the default value.
83 virtual bool apply_default(boost::any
& value_store
) const {
84 value_store
= _default
;
88 /// Notify the user function with the value of the value store.
89 virtual void notify(const boost::any
& value_store
) const {
90 if (_notifier
) _notifier(boost::any_cast
<T
>(value_store
));
93 virtual ~accumulator_type() {}
96 boost::function1
<void, const T
&> _notifier
;
102 accumulator_type
<T
>* accumulator() {
103 return new accumulator_type
<T
>();