[英]how do I make this function generic so that it accepts any container
我正在努力使用第二個功能。 我希望它像第一個一樣,但要接受List和vector
void draw__vec(vector<shape *> vs){
for(int i=0; i< vs.size();i++){
vs[i]->draw();
}
}
template <typename T>
void draw_generic(T<shape *> c){
}
一種方法是使用迭代器。
template <typename T>
void draw_generic(T c){
typename T::iterator beg = c.begin(), end = c.end();
while (beg != end) {
(*beg)->draw();
++beg;
}
}
為了使birryree的建議更具體,以下是它的外觀:
template <typename T>
void draw_generic(T begin, const T &end)
{
while(begin != end)
{
(*begin)->draw();
++begin;
}
}
現在,其用法將如下所示:
vector<shape *> shapearray;
list<shape *> shapelist;
// do something with those shapes
// ..
draw_generic(shapearray.begin(), shapearray.end());
draw_generic(shapelist.begin(), shapelist.end());
更多c ++ 11-ish:
template <typename Container>
void Draw(Container c)
{
for_each(begin(c), end(c), [](Shape* curr)
{
curr->draw();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.