1

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?

JensB
  • 839
  • 4
  • 19
  • See ["Pack expansion"](https://en.cppreference.com/w/cpp/language/parameter_pack#Pack_expansion): `"A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order."`. – G.M. Nov 21 '21 at 14:08
  • 1
    `foo()...` => `foo(), foo(), foo, etc.` – super Nov 21 '21 at 14:08

1 Answers1

3

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.

Thomas Caissard
  • 846
  • 4
  • 10