Ussu20
Ussu20

Reputation: 199

Is it mandatory to have a function template to pass std::vector as an argument?

Is it mandatory to have a function template to pass std::vector as an argument as in the below code?

Also, in the parameter, why do we need to pass <T> along with std::vector?

template <typename T>
void print_vec(const std::vector<T>& vec){
    for(size_t i{}; i < vec.size();++i){
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;    
}


int main(){

    //Constructing vectors
    std::vector<std::string> vec_str {"The","sky","is","blue","my","friend"};
    std::cout << "vec1[1]  : " << vec_str[1] << std::endl;
    print_vec(vec_str);
}

Upvotes: 1

Views: 115

Answers (2)

Pepijn Kramer
Pepijn Kramer

Reputation: 12872

Note in C++20 you can use this syntax, and it basically restricts your template to anything "iteratable" It also shows that in the case of ranges (vectors) you really should be using range based for loops. (Regrettably most C++ courses are somehwat out of date and don't show you this)

#include <vector>
#include <ranges>
#include <iostream>

// Use C++20 template/concept syntax
auto print_all(std::ranges::input_range auto&& values)
{
    for(const auto& value : values)
    {
        std::cout << value << "\n";
    }
}

int main()
{
    std::vector<std::string> values{"1","2","3"};
    print_all(values);
}

Upvotes: 2

Caleth
Caleth

Reputation: 62694

No, it isn't mandatory. The author thought that a template print_vec was more useful than a print_vec that was specific to std::vector<std::string>.

Upvotes: 3

Related Questions