Search code examples
c++templatesstliterator

Initializing a vector of auto (unknown) type inside a template function in C++


I have a template function inside which I want to generate a vector which is of an unknown type. I tried to make it auto, but compiler says it is not allowed.

The template function gets either iterators or pointers as seen in the test program inside the followed main function. How can the problem be fixed?

template<class Iter>
auto my_func(Iter beg, Iter end)
{
    if (beg == end)
        throw domain_error("empty vector");

    auto size = distance(beg, end);

    vector<auto> temp(size); // <--HERE COMPILER SAYS CANNOT BE AUTO TYPE
    copy(beg, end, temp->begin);
    .
    .
    return ....

}


int main()
{
    int bips[] = {3, 7, 0, 60, 17}; // Passing pointers of array
    auto g = my_func(bips, bips + sizeof(bips) / sizeof(*bips));

    vector<int> v = {10, 5, 4, 14}; // Passing iterators of a vector
    auto h = my_func(v.begin(), v.end());

    return 0;
}

Solution

  • You cannot use a std::vector of auto. You might use std::iterator_traits instead:

    std::vector<typename std::iterator_traits<Iter>::value_type> temp(size);