Sometimes there is a need to execute a particular function once and than switch to another implementation.
For example, I am really annoyed by the stream output iterator which prints delimiter after the item being printed in conjunction with the copy algorithm:
> 1,2,3,4,
^---- this is what happens in that case
The question isn't about nicely printing items, but more about properly concatenating them.
For example Python produces a correct result using string.join function:
','.join((1,2,3,4))
> 1,2,3,4
I also want to avoid if/else statement, because we only need once to make the switch after the first execution. So what I came up with, is:
std::function<char const*()> get_delim;
get_delim = [&get_delim]()
{
get_delim = [](){ return ","; };
return "";
};
for(auto b : some_byte_range)
std::cout << get_delim() << b;
Note: b is just a byte in my case, that's why I did not use auto const&.
Now the questions:
- Is there a way to get rid of the prior
std::function<char const*()>declaration and somehow declareget_delimwithautowhich effectively involves self-capturing of lambda? - Is there may be another more expressive (like in Python) way to do that kind of
join?