使用模板打印任何容器的所有数据 [英] use template to print all the data of any container

查看:77
本文介绍了使用模板打印任何容器的所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划编写一个可以打印任何容器的所有数据的函数。换句话说,我可以使用不同的容器类型(例如vector,deque或list),也可以使用不同的数据类型(整数,双精度或字符串)来调用它。
模板函数可以传递编译器,但我不知道如何调用它。

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

错误消息:
main.cpp:35:20:错误:没有匹配函数可调用'print(std :: list&)'
main.cpp:35:20:注意:候选者是:
main.cpp:21:6:注意:模板类M> void print(M)

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)

一些相关线程:
用于多种容器和数据类型的模板函数
http://louisdx.github.io/cxx-prettyprint/

推荐答案

如注释中所述, std :: list 实际上具有多个模板参数(第二个参数是分配器)。此外,不需要 print 来获取两个模板参数;您可以简单地在整个容器类型上对其进行参数化:

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

演示

如另一答案所指出,如果您可以使用C ++ 11功能, range-for循环比上面的显式迭代器更好。如果不能(这意味着没有 auto std :: begin std: :end ),然后:

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

请注意,因为我们采用数据通过const引用,我们需要使用 const_iterator

Note that since we take data by const reference, we need to use const_iterator.

这篇关于使用模板打印任何容器的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆