Using fold expressions to print all variadic arguments with newlines inbetween

前端 未结 2 863
耶瑟儿~
耶瑟儿~ 2021-02-20 03:54

The classic example for C++17 fold expressions is printing all arguments:

template
void print(Args ... args)
{
    (cout << ... &l         


        
2条回答
  •  时光取名叫无心
    2021-02-20 04:22

    repeat takes a function object f, and return a new function object. The return value runs f on each of its args. It "repeats" f on each of its args.

    template
    auto repeat( F&& f ) {
      return [f=std::forward(f)](auto&&...args)mutable{
        ( void(f(args)), ... );
      };
    }
    

    Use:

    repeat
    ( [](auto&&x){ std::cout << x << "\n"; } )
    ( args... );
    

    This uses fold expressions, but only indirectly. And honestly, you could have written this in C++14 (just the body of repeat would be uglier).

    We could also write a streamer that works with << to do it "more inline" and use fold expressions directly:

    template
    struct ostreamer_t {
      F f;
      friend std::ostream& operator<<( std::ostream& os, ostreamer_t&& self ) {
        std::move(self).f(os);
        return os;
      }
    };
    
    template
    ostreamer_t ostreamer( F&& f ) { return {std::forward(f)}; }
    

    then we use it like this:

    (std::cout << ... << ostreamer([&](auto&& os){ os << " " << args;}));
    

    ostreamer takes a function object. It returns an object that overloads << such that when you pass it an ostream on the left, it invokes the function object with the ostream.

    No temporary stream is created.

    Live examples.

提交回复
热议问题