Search code examples
c++variadic-templatesvariadic-functions

Why can't this argument pack be unpacked directly into a vector initializer list?


I don't understand why the commented out line in the code fragment doesn't work. Additionally, what is the actual type of vec? It looks like it could match the initialization format of a std::list as well.

I've looked through this and this question is what finally gave me the working solution, but now I don't understand why that works and the commented line doesn't, or how you can know the actual type (and therefore time/memory complexities of) vec.

#include <iostream>
#include <vector>


template <class ...T>
void func(T... arg_name) {
    // std::vector<T> vec{arg_name...};
    auto vec{arg_name...};
    for (auto i : vec) {
        std::cout << i << std::endl; 
    }
}


int main()
{
    func(1, 2, 3, 4);
}

The error message I get when I uncomment std::vector<T> vec{arg_name...} and comment out auto vec{arg_name...} is

In function 'void func(T ...)':
8:20: error: parameter packs not expanded with '...':
8:20: note:         'T'
10:19: error: range-based 'for' expression of type 'auto' has incomplete type

Solution

  • T is parameter pack, but vector takes one type parameter as type of elements, you can use common_type to select it:

    std::vector<std::common_type_t<T...>> vec{arg_name...};