Guest User

Untitled

a guest
Jan 17th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <typename... T>
  4. void foo(int a, int b) {
  5. auto sep = [first=true]() mutable { return first? (first = false, "") : ", "; };
  6.  
  7. std::cout << "foo(";
  8. if (a) std::cout << sep() << "a:" << a;
  9. if (b) std::cout << sep() << "b:" << b;
  10. std::cout << ")n";
  11. }
  12.  
  13. int main() {
  14. foo(0,0);
  15. foo(0,1);
  16. foo(2,3);
  17. foo(4,0);
  18. }
  19.  
  20. template <typename T = bool, T initial = true, T fallback = false>
  21. struct once {
  22. mutable T flag = initial;
  23.  
  24. operator T() const {
  25. T retval = fallback;
  26. std::swap(retval, flag);
  27. return retval;
  28. }
  29. };
  30.  
  31. auto sep = [first=once{}]{ return first? "" : ", "; };
  32.  
  33. auto sep = one_off("", ", ");
  34.  
  35. template <typename T = char const*>
  36. struct one_off {
  37. mutable once<> flag;
  38.  
  39. T first, other;
  40. one_off(T first, T other) : first(std::move(first)), other(std::move(other)) {}
  41.  
  42. operator T() const { return flag? first : other; }
  43. };
  44.  
  45. void foo(int a, int b) {
  46. auto sep = one_off("", ", ");
  47.  
  48. std::cout << "foo(";
  49. if (a) std::cout << sep << "a:" << a;
  50. if (b) std::cout << sep << "b:" << b;
  51. std::cout << ")n";
  52. }
  53.  
  54. void foo(std::vector<int> const& v) {
  55. auto sep = [n=0u]() mutable {
  56. if (n++)
  57. return n%5==1?"n" : ", ";
  58. return "";
  59. };
  60.  
  61. for (auto& el : v)
  62. std::cout << sep() << std::setw(5) << el;
  63. std::cout << "n";
  64. }
Add Comment
Please, Sign In to add comment