0

Imagine I have this function template:

template<auto& ... FLAGS>
void function(const char *c_str) {
    std::stringstream strs;
    //((strs << FLAGS)...); // <-- how do I do this?
    strs << c_str;
    .
    .
    .
}

Consider that the function template is going to be used like this:

function<std::dec, std::left>("123");

how to apply the operator << on each parameter from the parameter pack (with the object strs )?

I have already found a workaround with introducing a helper function:

void unpack(const auto& ...){};

And in the original function template:

unpack((strs << FLAGS)...);

But I was wondering if there is a better way to this!

newbie
  • 415
  • 3
  • 11

2 Answers2

1

The expression

strs << FLAG1 << FLAG2 << FLAG3;

is equal to

(((strs << FLAG1) << FLAG2) << FLAG3);

You have to chain operators, therefore you need the form of fold-expression

( cast-expression fold-operator ... fold-operator cast-expression )

where fold-operator is stringstream::operator<<

(strs << ... << FLAGS);
Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
1

Instead a fold with the << operator, you could also fold with the , operator, which would produce something like

str << FLAG1;
str << FLAG2;
...

(actually you'd need to use , instead of ; but the resulting logic is the same).

template<auto& ... FLAGS>
void function(int c_str) {
    std::stringstream strs;
    ((strs << FLAGS), ...);
    //              ^
    strs << c_str;
}
fabian
  • 80,457
  • 12
  • 86
  • 114