Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Note also that 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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading