Skip to content

Commit 775e950

Browse files
committed
Add cast operator from ranget to a container
Adding `.collect` to the end of a chain of range operations can add clutter to the code, rather than improving readability, in places where the type of container being constructed is apparent from the context. This commit adds a cast operation in order to improve readability in this scenario. In addition to the operator, this commit includes a refactor of `optionst::to_json` in order to demonstrate an example usage of the proposed change.
1 parent 97b4797 commit 775e950

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

src/util/options.cpp

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ Author: Daniel Kroening, [email protected]
1111

1212
#include "options.h"
1313

14+
#include "constructor_of.h"
1415
#include "json.h"
16+
#include "range.h"
1517
#include "string2int.h"
1618
#include "xml.h"
1719

@@ -90,14 +92,12 @@ const optionst::value_listt &optionst::get_list_option(
9092
/// Returns the options as JSON key value pairs
9193
json_objectt optionst::to_json() const
9294
{
93-
json_objectt json_options;
94-
for(const auto &option_pair : option_map)
95-
{
96-
json_arrayt &values = json_options[option_pair.first].make_array();
97-
for(const auto &value : option_pair.second)
98-
values.push_back(json_stringt(value));
99-
}
100-
return json_options;
95+
return make_range(option_map)
96+
.map([](const std::pair<std::string, value_listt> &option_pair) {
97+
return std::pair<std::string, json_arrayt>{
98+
option_pair.first,
99+
make_range(option_pair.second).map(constructor_of<json_stringt>())};
100+
});
101101
}
102102

103103
/// Returns the options in XML format

src/util/range.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,12 @@ struct ranget final
359359
return {begin(), end()};
360360
}
361361

362+
template <typename containert>
363+
operator containert() const
364+
{
365+
return collect<containert>();
366+
}
367+
362368
private:
363369
iteratort begin_value;
364370
iteratort end_value;

0 commit comments

Comments
 (0)