簡體   English   中英

如何使用 std:string 參數迭代可變參數函數?

[英]How to iterate over variadic function with std:string arguments?

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

   // do something with every argument

}

假設我希望能夠獲取每個字符串參數並在將其打印到新行之前附加一個感嘆號。

最好的方法是使用參數 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!

C++17

使用帶有fold expressionparameter pack

#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;
}

這是一個迭代解決方案。 函數調用中有一點噪音,但不需要計算可變參數的數量。

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM