Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use "one single template parameter" for several different "std::class types"?

Tags:

c++

templates

-Hello everyone, I'm pretty much a beginner. -Is there anyway that I can merge "the 2 following function templates" into a single one? , like we can use T3= { std::list<T || std::forward_list } and then merge these 2 functions into one? -My heavy gratitude in advance :) .

#include <iostream>
#include <list>
#include <forward_list>

template <class T> void prinList(std::list<T> list){
    for (auto var : list){ std::cout << var << " "; }
    std::cout << '\n';
}
template <class T> void prinList(std::forward_list<T> list){
    for (auto var : list){ std::cout << var << " "; }
    std::cout << '\n';
}
int main(){
    std::forward_list<int> F_list1={1,2,3,4,5};
    prinList(F_list1);

    std::list<int> list1={10,11,12,13};
    prinList(list1);

    return 0;
}
like image 657
Rango Avatar asked Sep 13 '25 21:09

Rango


1 Answers

You can do it the following way:

#include <iostream>
#include <list>
#include <forward_list>

template <class T> void prinList(T const & list) {
    for (auto var : list) { std::cout << var << " "; }
    std::cout << '\n';
}

int main() {
    std::forward_list<int> F_list1 = { 1,2,3,4,5 };
    prinList(F_list1);

    std::list<int> list1 = { 10,11,12,13 };
    prinList(list1);

    return 0;
}

Output:

1 2 3 4 5
10 11 12 13

Live demo - Godbolt

Notes:

  1. The list parameter is accepted by a const & to avoid copy and also protect against attempt to modify the list.

  2. list can be in fact any container or similar class that supports the range-based loop, making the function more generic (you might want to rename it accordingly).

like image 179
wohlstad Avatar answered Sep 16 '25 12:09

wohlstad