Search code examples
c++templatesc++17variadic-templates

How recursive variadic templates is work?


With this code:

static unsigned count = 0;

template<typename... T>
auto sum(T... args)
{
    ++count;
    return (... + args);
}

int main (void)
{
    std::cout << sum(12, 32, 32, 12, 4, 3, 43, 432) << std::endl;
    std::cout << "TIME: " << count << std::endl;
}

Output is:

$> ./program.out
570
TIME: 1

Why is count equals to 1? I expected count to be 8. Is sum template function called only once?


Solution

  • Is sum template function call once ?

    Yes, it won't be called recursively. Instead, the expression is expanded for fold expression.

    The instantiation of a fold expression expands the expression e as follows:

    ...
    2) Unary left fold (... op E) becomes (((E1 op E2) op ...) op EN)
    ...

    (where N is the number of elements in the pack expansion)

    You might want to put ++count into the fold expression, e.g.

    template<typename... T>
    auto sum(T... args)
    {
        return (... + (++count, args));
    }
    

    As @Xatyrian pointed, its value is just same as the number of elements in the pack expansion, which could be taken by sizeof... too.