Home > Software engineering >  Why does passing a parameter pack to a function with one template parameter call it multiple times?
Why does passing a parameter pack to a function with one template parameter call it multiple times?

Time:11-28

Take this code:

template<typename T>
int foo()
{
    std::cout << "foo called" << std::endl;
    return 10;
};

template<typename... Ts>
std::vector<int> bar(Ts... ts)
{
    std::vector<int> vec{foo<Ts>()...};
    return vec;
};

int main()
{
    std::vector<int> vec = bar(1,2,3,4);
}

The code above outputs:

foo called
foo called
foo called
foo called

How is this possible? I thought I had understood template parameter packs, but how does the line std::vector<int> vec{foo<Ts>()...}; cause foo to be called multiple times? Is foo returning a parameter pack, since we use the ... operator on the function call?

What's going on this code?

CodePudding user response:

foo<T>()... is expanded to foo<T1>(), foo<T2>(), foo<T2>(), .... In your case, since your vector has four components, your function will be called four times with the expansions.

  • Related