Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range/Loop through N variables in [modern] C++

What's a succinct way of ranging through N variables, of any type each, to perform an operation?

Let's say I have variables a, b, c, d, e and want to go through all of them performing some operation.

like image 659
pepper_chico Avatar asked Jan 24 '26 02:01

pepper_chico


2 Answers

Use Boost.Hana and generic lambdas:

#include <tuple>
#include <iostream>
#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>

struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

int main() {
    using namespace std;
    using boost::hana::for_each;

    A a;
    B b;
    C c;
    D d;
    E e;

    for_each(tie(a, b, c, d, e), [](auto &x) {
        cout << typeid(x).name() << endl;
    });
}

http://coliru.stacked-crooked.com/a/ccb37ec1e453c9b4

like image 146
pepper_chico Avatar answered Jan 25 '26 15:01

pepper_chico


You may use: (C++11) (https://ideone.com/DDY4Si)

template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    const int dummy[] = { (f(std::forward<Ts>(args)), 0)... };
    static_cast<void>(dummy); // avoid warning about unused variable.
}

With F a functor (or a generic lambda (C++14)). You may call it like this in C++14:

apply([](const auto &x) { std::cout << typeid(x).name() << std::endl;}, a, b, c, d, e);

In C++17, with folding expression, it would be:

template <typename F, typename...Ts>
void apply(F f, Ts&&...args) {
    (static_cast<void>(f(std::forward<Ts>(args))), ... );
}
like image 44
Jarod42 Avatar answered Jan 25 '26 15:01

Jarod42