首頁 > 後端開發 > C++ > 主體

如何在 C 中有效地迭代打包的可變參數模板參數列表?

Barbara Streisand
發布: 2024-10-23 18:21:59
原創
482 人瀏覽過

How to Effectively Iterate Over Packed Variadic Template Argument Lists in C  ?

迭代打包的可變參數範本參數清單

簡介

可變參數範本可讓您建立可以使用參數範本數量可變。然而,迭代這些論點可能具有挑戰性。本文探討了迭代打包可變參數模板參數清單的方法,包括使用折疊表達式的綜合解決方案。

方法 1:迭代同質類型輸入

如果您的輸入都是相同的類型,您可以使用宏或 lambda 函數來循環它們。例如:

<code class="cpp">#include <iostream>

#define FOREACH_INPUT(...) (([](auto &&... inputs) { for (auto input : { __VA_ARGS__ }) { std::cout << input << std::endl; } })(inputs))</code>
登入後複製

用法:

<code class="cpp">FOREACH_INPUT(1, 2, 3, 4, 5);</code>
登入後複製

方法2:折疊表達式(>= C 17)

對於混合-類型輸入,折疊表達式提供了一種簡潔而強大的方法。請考慮以下範例:

<code class="cpp">#include <iostream>
#include <utility>

template <class ... Ts>
void Foo (Ts &&... inputs)
{
    int i = 0;

    ([&amp;]
    {
        std::cout << "input " << ++i << " = " << inputs << std::endl;
    } (), ...);
}

int main()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>
登入後複製

具有中斷/返回的增強折疊表達式

如果您的循環中需要中斷或返回,請考慮以下解決方法:

  • 嘗試/拋出:
<code class="cpp">#include <iostream>
#include <utility>

template <class ... Ts>
void Foo (Ts &&... inputs)
{
    int i = 0;

    try {
        ([&amp;]
        {
            std::cout << "input " << ++i << " = " << inputs << std::endl;
            if (inputs == 'a') throw 1;
        } (), ...);
    } catch (...) {
    }
}

int main()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>
登入後複製
  • 變量/If 開關:
<code class="cpp">#include <iostream>
#include <utility>

template <class ... Ts>
void Foo (Ts &&... inputs)
{
    int i = 0;
    bool exit = false;

    auto process_input = [&amp;](auto &amp;&amp;input) mutable {
        if (input == 'a') {
            std::cout << "Found 'a'. Breaking loop." << std::endl;
            exit = true;
            return;
        }
        std::cout << "input " << ++i << " = " << input << std::endl;
    };

    (process_input(inputs), ...);
    if (!exit)
        std::cout << "Finished looping through all inputs." << std::endl;
}

int main()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>
登入後複製

以上是如何在 C 中有效地迭代打包的可變參數模板參數列表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!