fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<typename Iterator, typename Fn1, typename Fn2>
  5. void for_the_device(Iterator from, Iterator to, Fn1 always, Fn2 butFirst) {
  6. switch ((from == to) ? 1 : 2) {
  7. case 0:
  8. do {
  9. butFirst(*from);
  10. case 2:
  11. always(*from); ++from;
  12. } while (from != to);
  13. default: // reached directly when from == to
  14. break;
  15. }
  16. }
  17.  
  18. int main() {
  19. int const items[] = {21, 42, 63};
  20. int const * const end = items + sizeof(items) / sizeof(items[0]);
  21. for_the_device(items, end,
  22. [](auto const & i) { cout << i;},
  23. [](auto const & i) { cout << ", ";});
  24. cout << endl << "I'm (still) so sorry" << endl;
  25. // Now on an empty range
  26. for_the_device(end, end,
  27. [](auto const & i) { cout << i;},
  28. [](auto const & i) { cout << ", ";});
  29. cout << "Incredibly sorry." << endl;
  30. return 0;
  31. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
21, 42, 63
I'm (still) so sorry
Incredibly sorry.