Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template <typename... T>
- void foo(int a, int b) {
- auto sep = [first=true]() mutable { return first? (first = false, "") : ", "; };
- std::cout << "foo(";
- if (a) std::cout << sep() << "a:" << a;
- if (b) std::cout << sep() << "b:" << b;
- std::cout << ")n";
- }
- int main() {
- foo(0,0);
- foo(0,1);
- foo(2,3);
- foo(4,0);
- }
- template <typename T = bool, T initial = true, T fallback = false>
- struct once {
- mutable T flag = initial;
- operator T() const {
- T retval = fallback;
- std::swap(retval, flag);
- return retval;
- }
- };
- auto sep = [first=once{}]{ return first? "" : ", "; };
- auto sep = one_off("", ", ");
- template <typename T = char const*>
- struct one_off {
- mutable once<> flag;
- T first, other;
- one_off(T first, T other) : first(std::move(first)), other(std::move(other)) {}
- operator T() const { return flag? first : other; }
- };
- void foo(int a, int b) {
- auto sep = one_off("", ", ");
- std::cout << "foo(";
- if (a) std::cout << sep << "a:" << a;
- if (b) std::cout << sep << "b:" << b;
- std::cout << ")n";
- }
- void foo(std::vector<int> const& v) {
- auto sep = [n=0u]() mutable {
- if (n++)
- return n%5==1?"n" : ", ";
- return "";
- };
- for (auto& el : v)
- std::cout << sep() << std::setw(5) << el;
- std::cout << "n";
- }
Add Comment
Please, Sign In to add comment