3

I want to use boost hana to generate this final code:

template < typename ... Ts >
void  foo(Ts ... data) {

  constexpr auto tuple = hana::make_tuple(data...);

  //Code that I need to be generate
  container_c[tuple[0_c]].foo2();
  container_c[tuple[1_c]].foo2();
  container_c[tuple[2_c]].foo2();
}

container_c is a map generate at compile time, I'm don't think that it really matter here though. foo2 is not constexpr.

I was thinking using hana::size(tuple).times but I need an increment, probably using hana::make_range(hana::size_c<0>, hana::size(tuple)) and I don't know how to do it.

I was hoping to find a function which will allow me to execute a function on each member of my tuple inside hana. Something like hana::transform but for void lambda.

I didn't expect to have some hard time finding how to do it with Hana, should I just use a specialization like in the old times?

Btw, I'm using gcc 7.1 right now, but you can work on the assumption that I have no compiler restrictions.

Mathieu Van Nevel
  • 1,428
  • 1
  • 10
  • 26

1 Answers1

4

To iterate over your data, you may do

template < typename ... Ts >
void  foo(Ts ... data) {
    int dummy[] = {0, (container_c[data].foo2(), void(), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable.
}

Or in C++17

template < typename ... Ts >
void  foo(Ts ... data) {
    (static_cast<void>(container_c[data].foo2()), ...);
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 3
    Note that [C++17 fold expressions](http://en.cppreference.com/w/cpp/language/fold) make this a lot less ugly, if the OP's compiler supports them. –  Aug 13 '17 at 10:28
  • Seems like you want to initialize an array to iterate over? But I don't get this syntax at all. And the loop will be done at runtime then no? Btw I don't have any compiler restrictions, I will edit my question for that. – Mathieu Van Nevel Aug 13 '17 at 10:35
  • @hvd: Add C++17 version. – Jarod42 Aug 13 '17 at 13:52
  • Oh I got it with the C++17 version :) Thanks, I did try something like that, I should learn more about fold expressions. – Mathieu Van Nevel Aug 13 '17 at 16:00