Nifty Fold Expression Tricks--Jonathan Müller

Many things can be done!

Nifty Fold Expression Tricks

by Jonathan Müller

From the article:

Suppose you need to have a variadic function and want to add all arguments together. Before C++17, you need two pseudo-recursive functions:

  1. template <typename H, typename ... T>
  2. auto add(H head, T... tail)
  3. {
  4. return head + add(tail...);
  5. }
  6.  
  7. template <typename H>
  8. auto add(H head)
  9. {
  10. return head;
  11. }

However, C++17 added fold expressions, making it a one-liner:

  1. template <typename H, typename ... T>
  2. auto add(H head, T... tail)
  3. {
  4. return (head + ... + tail);
  5. // expands to: head + tail[0] + tail[1] + ...
  6. }

If we’re willing to abuse operator evaluation rules and fold expressions, we can do a lot more. This blog posts collects useful tricks…

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.