Home > Mobile >  Pass parameter pack to function repeatedly
Pass parameter pack to function repeatedly

Time:02-16

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?

CodePudding user response:

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.

  • Related