如何使用 std:string 个参数迭代可变参数函数?
How to iterate over variadic function with std:string arguments?
void foo(std::string arg, ...) {
// do something with every argument
}
假设我希望能够获取每个字符串参数并在将其打印到新行之前附加一个感叹号。
最好的方法是使用parameters 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;
}
这将打印出:
qwe!
asd!
这是一个迭代解决方案。函数调用中有一点噪音,但不需要计算可变参数的数量。
#include <iostream>
#include <string>
#include <initializer_list>
#include <functional> // reference_wrapper
void foo(std::initializer_list<std::reference_wrapper<std::string>> args) {
for (auto arg : args) {
arg.get().append("!");
}
}
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;
}
C++17
使用 parameter pack
with a fold expression
:
#include <iostream>
#include <string>
// Modify multiple strings. Here we use parameters pack by `...T`
template<typename ...T>
void foo(T&... args)
{
(args.append("!"),...);
}
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;
}
void foo(std::string arg, ...) {
// do something with every argument
}
假设我希望能够获取每个字符串参数并在将其打印到新行之前附加一个感叹号。
最好的方法是使用parameters 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;
}
这将打印出:
qwe!
asd!
这是一个迭代解决方案。函数调用中有一点噪音,但不需要计算可变参数的数量。
#include <iostream>
#include <string>
#include <initializer_list>
#include <functional> // reference_wrapper
void foo(std::initializer_list<std::reference_wrapper<std::string>> args) {
for (auto arg : args) {
arg.get().append("!");
}
}
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;
}
C++17
使用 parameter pack
with a fold expression
:
#include <iostream>
#include <string>
// Modify multiple strings. Here we use parameters pack by `...T`
template<typename ...T>
void foo(T&... args)
{
(args.append("!"),...);
}
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;
}