C++ Logo

std-discussion

Advanced search

Re: generic c++ for loop

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 26 Nov 2024 08:14:36 -0800
On Monday 25 November 2024 18:48:10 Pacific Standard Time Yongwei Wu via Std-
Discussion wrote:
> void printWithSeparator(const T& sep, const Args&... args)
>
> {
>
> ((cout << args << sep), ...);
>
> }
>
> Replace with the `(cout << args << sep)` part with what you want to do with
> the arguments.

Experience says that fold operations run into compiler-imposed limits faster
than regular template expansions. You can convert one into the other this way
though:

  auto print = [&sep](const auto &arg) { cout << arg << sep; return 0; };
  int dummy[] = { print(args)..., 0 };
  (void) dummy;

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2024-11-26 16:14:39