use template to print all the data of any container

蹲街弑〆低调 提交于 2019-12-02 18:12:35

问题


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/


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23719297/use-template-to-print-all-the-data-of-any-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!