-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;
}
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:
The list
parameter is accepted by a const &
to avoid copy and also protect against attempt to modify the list.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With