Reputation: 13
I plan to write a function which can print all the data of any container. In other words, I can use with different containers type like vector, deque or list and that I can call it with different data types ( integers , double or string). The template function can pass the compiler, but I do not know how to call it.
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <list>
using namespace std;
template <typename C, template <typename C> class M>
void print(M<C> data){
typename M<C>::iterator it;
for(it=data.template begin();it!=data.template end();++it){
cout<<*it<<" ";
}
cout<<endl;
}
int main(int argc, char** argv) {
list<int> data;
for(int i=0;i<4;i++){
data.push_back(i);
}
print<int>(data); //compile error
print<int, list>(data); //compile error
return 0;
}
error message: main.cpp:35:20: error: no matching function for call to 'print(std::list&)' main.cpp:35:20: note: candidate is: main.cpp:21:6: note: template class M> void print(M)
some related threads: template function for multiple containers and data types http://louisdx.github.io/cxx-prettyprint/
Upvotes: 0
Views: 2059
Reputation: 137310
As noted in the comments, std::list
actually has more than one template parameter (the second parameter is the allocator). Moreover, there is no need for print
to take two template parameters; you can simply parameterize it over the overall container type:
#include <iostream>
#include <iterator>
#include <list>
using namespace std;
template <typename C>
void print(const C &data){
for(auto it=begin(data);it!=end(data);++it){
cout<<*it<<" ";
}
cout<<endl;
}
int main(int argc, char** argv) {
list<int> data;
for(int i=0;i<4;i++){
data.push_back(i);
}
print(data);
return 0;
}
Demo.
As pointed out in the other answer, if you can use C++11 features, a range-for loop is better than the explicit iterator use above. If you can't (which means no auto
or std::begin
or std::end
either), then:
template <typename C>
void print(const C &data){
for(typename C::const_iterator it=data.begin();it!= data.end();++it){
cout<<*it<<" ";
}
cout<<endl;
}
Note that since we take data
by const reference, we need to use const_iterator
.
Upvotes: 3
Reputation: 127
Using c++11 you can simplify it to:
template <typename C>
void print(const C &data){
for (auto &elem : data)
cout << elem << " ";
cout << endl;
}
and call it with print(data)
. You could also use std::for_each
or copy it directly into cout.
Upvotes: 2