多个容器和数据类型的模板函数 [英] template function for multiple containers and data types
问题描述
我想创建一个模板函数,我可以使用不同的容器类型像矢量,deque或列表,我可以调用它与不同的数据类型(整数,双或字符串),我搜索,但could'n找不到答案,我试过这样做,但我收到错误:
I want to create a template function that 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), I've searched but could'n't find an answer , I've tried doing it like this, but I'm getting errors:
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <iterator>
#include <string>
using namespace std;
template <typename C>
void printvec(const C& numbers1)
//void printvec(container C<typename C::valuetype T>)
{
//C &numbers1;
for(auto i=0; i < numbers1.size(); ++i)
cout<<&numbers1<<endl;
//typename C<A>::iterator itr;
//for ( itr=numbers1.begin();itr != numbers1.end(); ++itr)
// cout<<*itr<<endl;
}
int main()
{
vector<int> vint{2,4,6,8,9,3};
vector<double> vdouble{5.8, 6.7, 7.3};
vector<string> vstring {"alex", "bbb", "cccc"};
list<int> ls{1,2,3,4,5};
printvec(vint );
printvec(vdouble);
printvec(vstring);
printvec(ls);
return 0;
}
那么,正确的做法是什么? >
so, what is the right way to do it, please?
推荐答案
其他人已经指出了为什么应该使用库函数以及为什么要重新发明轮子。
Others have pointed out why you should use a library function and why you are reinventing the wheel. Here is how you should have written it, if you want to do it.
容器不是以抽象基类的形式指定的,而是一个指定所需语法的通用接口和句法结构的预期语义(这些东西被称为概念)。最常见的是 Container ,更专业的是 SequenceContainer 。如果您接受 SequenceContainer
作为模板参数,那么必须约束使用模板参数的代码。在您的情况下:
Containers are not specified in terms of abstract base-classes but a generic interface that specifies required syntax and expected semantics of syntactical constructions (those things are called concepts). The most general is Container, a more specialized one is SequenceContainer. If you accept a SequenceContainer
as a template argument you must constrain code that uses the template argument to those requirements. In your case:
template<typename SequenceContainer>
void print(const SequenceContainer& seq)
{
// being able to use range-for loops
// is a consequence of being a SequenceContainer
for(auto& i : seq) {
std::cout << i << " ";
}
std::cout << std::endl;
// alternatively
using std::begin; // enable ADL fallback for arrays
using std::end;
for(auto it = begin(seq); it != end(seq); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
编写良好的模板代码不是为了微弱的心,所以你可能
想要考虑更好地了解基本的C ++。
Writing good template code is not for the faint of heart, so you might want to consider getting a better understanding of basic C++ first.
这篇关于多个容器和数据类型的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!