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

时间:2011-11-30 03:01:06

标签: c++

我正在努力解决第二个问题。我想它就像第一个但接受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){

}

3 个答案:

答案 0 :(得分:2)

一种方法是使用迭代器。

template <typename T>
void draw_generic(T c){
    typename T::iterator beg = c.begin(), end = c.end();

    while (beg != end) {
       (*beg)->draw();
       ++beg;
    }
}

答案 1 :(得分:2)

为了使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());

答案 2 :(得分:1)

更多c ++ 11-ish:

template <typename Container>
void Draw(Container c)
{
    for_each(begin(c), end(c), [](Shape* curr)
    {
         curr->draw();
    });
}
相关问题