c++stdstdvectorfunction-templates

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);
}

Solution

  • 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>.