如何使用std:string参数遍历可变参数函数?

Jam*_*mes 2 c++ variadic

void foo(std::string arg, ...) {

   // do something with every argument

}
Run Code Online (Sandbox Code Playgroud)

可以说我希望能够接受每个字符串参数,并在将其打印到新行之前附加一个感叹号。

sta*_*nov 6

最好的方法是使用pack参数。例如:

#include <iostream>

// Modify single string.
void foo(std::string& arg)
{
    arg.append("!");
}

// Modify multiple strings. Here we use parameters pack by `...T`
template<typename ...T>
void foo(std::string& arg, T&... args)
{
    foo(arg);
    foo(args...);
}

int main()
{
    // Lets make a test

    std::string s1 = "qwe";
    std::string s2 = "asd";

    foo(s1, s2);

    std::cout << s1 << std::endl << s2 << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这将打印出:

qwe!
asd!
Run Code Online (Sandbox Code Playgroud)