0

I need to pass a parameter pack to a function repeatedly in a loop, like this:

void printString(string str)
{
    cout << "The string is: \"" << str << "\"" << endl;
}

template <typename FunctionType, typename ...Args>
void RunWithArgs(FunctionType functionToCall, Args...args)
{
    for (int i = 0; i < 3; i++)
        functionToCall(forward <Args>(args)...);
}

int main()
{
    string arg("something");
    RunWithArgs (printString, arg);
    
    return 0;
}

The compiler gives me a hint that I'm using a moved-from object, and sure enough, the string is only passed the first time:

The string is: "something"
The string is: ""
The string is: ""

How do I pass the parameter pack to the function on every iteration of the loop?

TS_
  • 75
  • 4

1 Answers1

1

In this line:

functionToCall(forward <Args>(args)...);

You are forwarding the argument, which in this case, moves it. If you don't want to move, but instead want to copy, then do that:

functionToCall(args...);

Here is a live example.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Alternately, change the signature to `void RunWithArgs(FunctionType functionToCall, Args&&... args)` so that perfect forwarding is possible. Example [here](https://godbolt.org/z/x7joh9f3W) – Nathan Pierson Feb 16 '22 at 07:25
  • @NathanPierson That won't work though if they want the same behaviour for an r-value: http://coliru.stacked-crooked.com/a/a64546a2de52dac0 – Fantastic Mr Fox Feb 16 '22 at 07:34