如何使用派生类的向量作为参数来实现功能 [英] How to implement function with vector of derived classes as parameter

查看:66
本文介绍了如何使用派生类的向量作为参数来实现功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(与我之前询问的未回答的问题有关).我想实现一个只能用相关类的向量作为参数来调用的函数.

(Related to a previous unanswered question I asked). I want to implement a function which can be called only with vectors of related classes as parameter.

对于

如果有

class A;
class B: public A;
class C: public A;
class D

then it should be possible to call function with vector<A*>,vector<B*> or 
vector <C*> but not vector <D*>

任何建议

推荐答案

我想您已经尝试创建类似的方法

I guess you already tried to create a method like

void doSomething(std::vector<A*>& things)
{
}

并尝试通过

std::vector<B*> bList = ...;
doSomething(bList);

对吗?

为什么编译器会抱怨?因为那没有意义.考虑到doSomething()试图做

Why does the compiler complain? Because it would not make sense. Consider that doSomething() tries to do

things.push_back(new C());

这不能工作,因为物"实际上是std::vector<B*>.但是,如果它是std::vector<A*>,则push_back将起作用.

This cannot work as "things" is actually a std::vector<B*>. However, if it were std::vector<A*>, push_back would work.

那么我们可以从中学到什么呢?仅当您从向量读取时,您尝试执行的操作才有意义,但是,向量不是只读容器.

So what can we learn from this? What you're trying only makes sense if you only read from the vector, however, vector is not a read-only container.

一个简单的包装器显示了一个可能的解决方案(当然,可以根据需要调整包装器).但是,我必须指出,使用虚拟方法可能会导致性能下降.

A simple wrapper shows a possible solution (the wrapper can be adjusted to your needs, of course). However, I have to point out that the use of virtual methods might lead to performance penalties.

class A {};
class B : public A {};

template <class Base>
class AbstractVectorWrapper
{
public:
    virtual size_t size() const = 0;
    virtual Base* getElementAt(int index) const = 0;
};
template <class Base, class Derived>
class VectorWrapper : public AbstractVectorWrapper<Base>
{
private:
    std::vector<Derived*> m_vector;
public:
    explicit VectorWrapper(std::vector<Derived*> const& vector)
        : m_vector(vector)
    {
    }
    virtual size_t size() const
    {
        return m_vector.size();
    }
    virtual Base* getElementAt(int index) const
    {
        return m_vector[index];
    }
};

void doSomething(AbstractVectorWrapper<A> const& wrapper)
{
    for (size_t i=0;i<wrapper.size();i++)
    {
        A* a = wrapper.getElementAt(i);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<A*> as;
    std::vector<B*> bs;
    doSomething(VectorWrapper<A,B>(bs));
    doSomething(VectorWrapper<A,A>(as));


    return 0;
}

这篇关于如何使用派生类的向量作为参数来实现功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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