繁体   English   中英

我如何使此函数通用,以便它接受任何容器

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM