>  기사  >  백엔드 개발  >  C에서 Packed Variadic 템플릿 인수 목록을 효과적으로 반복하는 방법은 무엇입니까?

C에서 Packed Variadic 템플릿 인수 목록을 효과적으로 반복하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-23 18:21:59487검색

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

패킹된 Variadic 템플릿 인수 목록 반복

소개

Variadic 템플릿을 사용하면 가변 개수의 인수. 그러나 이러한 인수를 반복하는 것은 어려울 수 있습니다. 이 문서에서는 접기 표현식을 사용하는 포괄적인 솔루션을 포함하여 압축된 가변 템플릿 인수 목록을 반복하는 방법을 살펴봅니다.

방법 1: 동종 유형 입력 반복

입력이 모두 동일한 유형이면 매크로나 람다 함수를 사용하여 반복할 수 있습니다. 예:

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

#define FOREACH_INPUT(...) (([](auto &&... inputs) { for (auto input : { __VA_ARGS__ }) { std::cout << input << std::endl; } })(inputs))

사용법:

<code class="cpp">FOREACH_INPUT(1, 2, 3, 4, 5);

방법 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에서 Packed Variadic 템플릿 인수 목록을 효과적으로 반복하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.