Folds(ish) in C++11

Save to:
Instapaper Pocket Readability

Folds of variadic expressions are coming in C++17, but what about today?

Folds(ish) in C++11

by Jason Turner

From the article:

It is possible to perform some form of the variadic folds that are coming in C++17 with the C++11 and C++14 compilers that we have available today by using just a little bit of creativity.

...

Someone (not me) figured out that we can abuse the std::initializer_list type to let us guarantee the order of execution of some statements while not having to recursively instantiate templates. For this to work we need to create some temporary object to let us use the braced initializer syntax and hold some result values for us.

Only problem is, our print function doesn’t return a result value. So what do we do? Give it a dummy return value!

#include <iostream>

template<typename T>
void print(const T &t)
{
  std::cout << t << '\n';
}

template<typename ... T>
  void print(const T& ... t)
{
  std::initializer_list<int>{ (print(t), 0)... };
}

int main()
{
  print(1, 2, 3.4, "Hello World");
}

...

(And we continue to simplify it much more from here...)

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.