Using fold expressions to print all variadic arguments with newlines inbetween

前端 未结 2 857
耶瑟儿~
耶瑟儿~ 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:18

    Update: T.C.'s comment below provided a better solution:

    template
    void print(Args ... args)
    {
        ((cout << args << '\n'), ...);
    }
    

    You can use a fold expression over the comma operator:

    template
    void print(Args ... args)
    {
        ([](const auto& x){ cout << x << "\n"; }(args), ...);
    }
    

    Usage:

    int main()
    {
        print("a", 1, 1000);
    }
    

    a

    1

    1000

    (Note: this prints a trailing newline as well.)

    • live wandbox example

    • assembly comparison on godbolt


    Explanation:

    • [](const auto& x){ cout << x << "\n"; } is a lambda that given x prints x and '\n'.

    • [](const auto& x){ cout << x << "\n"; }(args) immediately invokes the lambda with args.

    • ([](const auto& x){ cout << x << "\n"; }(args), ...) is a fold expression over the comma operator that expands in the following way:

      // (pseudocode)
      [](const auto& x){ cout << x << "\n"; }(args<0>),
      [](const auto& x){ cout << x << "\n"; }(args<1>),
      [](const auto& x){ cout << x << "\n"; }(args<2>),
      // ...
      [](const auto& x){ cout << x << "\n"; }(args)
      

提交回复
热议问题