Dump into output stream (procedural vs functional style)
In today post will be short. In one of my unit test I wanted to dump acquired MQTT messages as map of topic, payload pairs (map<string, string>
) into console output for debug purpose. This can be done an easy way in C++17 with following code
for (auto const & [topic, payload] : data)
cout << topic << " -> " << payload << ", ";
The last couple of months, I’ve had a change to try JS (with Ramda functional library) so I wanted to know how eqvivalent functional code would look like in C++20’s ranges or using Boost.Ranges.
So functional style with C++20’s std::ranges
// functional with std::ranges
copy(data|
transform([](auto const & e){
return e.first + " -> "s + e.second;
}),
std::ostream_iterator<string>{cout, ", "}
); //= a -> 1, b -> 2, c -> 3,
and the same, but in Boost.Ranges
// functional with Boost.Ranges
boost::copy(data|
boost::adaptors::transformed([](auto const & e){
return e.first + " -> "s + e.second;
}),
std::ostream_iterator<string>{cout, ", "}
); //= a -> 1, b -> 2, c -> 3,
where data
looks this way
map<string, string> data{ // (topic, payload) pair
{"a", "1"},
{"b", "2"},
{"c", "3"}
};
there is the full code sample.
Just for a sake of debugging unit test it is easier to use procedural approach (the first one) and get work done over the functional one.