Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

On the semantics of a range based for loop, and the violation thereof

18 views
Skip to first unread message

Daniel

unread,
Sep 18, 2018, 9:52:01 PM9/18/18
to
I have a JSON pull parser, re https://github.com/danielaparker/jsoncons, which sports a GOF style interface, an example being

std::string s = std::string s = R"(["one",2,"three"])";
std::istringstream is(s);

json_event_reader event_reader(is);

for (; event_reader.has_next(); event_reader.next())
{
const auto& event = event_reader.current();
switch (event.event_type())
{
case json_event_type::string_value:
std::cout << event.as<std::string>() << " ";
break;
case json_event_type::int64_value:
case json_event_type::uint64_value:
std::cout << event.as<std::string>() << " ";
break;
}
}

Output: one 2 three

I've thought about adding functions to the reader

iterator begin();
iterator end();

where type iterator is an InputIterator which invokes has_next(), next()
and current() on the reader, just to be able to write

for (const auto& event : event_reader)
{
switch (event.event_type())
{
case json_event_type::string_value:
std::cout << event.as<std::string>() << " ";
break;
case json_event_type::int64_value:
case json_event_type::uint64_value:
std::cout << event.as<std::string>() << " ";
break;
}
}

But is that too strange? Having a range-based for loop that mutates the
state of the reader and only allows one go around?

Thanks,
Daniel
0 new messages