Is unpacking variadic using array(or initializer_list) trick optimize-safe?

169 Views Asked by At

Since C++14 cannot use fold expression, in order to make a function that calls bar on each variadics, one have to use function overloading.

template<typename Arg>
void foo(Arg arg) {
  bar(arg);
}

template<typename Arg, typename ...Args>
void foo(Arg arg, Args... args) {
  bar(arg);
  foo(args...);
}

But using comma operator and parenthesis in bracket, one can unpack without overload.

template<typename ...Args>
void foo(Args... args) {
  int dummy[] = {
    (bar(args), 0)...
  };
}

It works well as expected, but my compiler always warns me that dummy is not used. So I'm worried that the compiler removes dummy(since it's unused and actually initialized only by literals), and resulting to not calling bar.
Or just declaring dummy as volatile is enough to be guarantee that bar is called?
I know that there is [[maybe_unused]] attribute, but it's also C++17 feature.

2

There are 2 best solutions below

0
On BEST ANSWER

So I'm worried that the compiler removes dummy(since it's unused and actually initialized only by literals), and resulting to not calling bar.

Compiler might remove dummy but cannot remove bar calls if they have side effects (as for the recursive version).

So you are safe.

Or just declaring dummy as volatile"

That is worst. As you force the write. You remove the warning the wrong way.

I know that there is [[maybe_unused]] attribute, but it's also C++17 feature.

Casting to void is a common way to remove the warning, previously.

0
On

no worry, the compiler optimizations won't break the code behavior otherwise the compiler is broken, however there is copy eliding and such which changes the behavior in a documented way .

in your case the the call will be evaluated and the return value stored in the array is discarded. since this is your intention you can get rid of this warning by using the variable !

((void)dummy);