开发者

c++ cast vector<Inherited*> to vector<abstract*>

class Interface{};

class Foo: public Interface{};

class Bar{
public:开发者_开发技巧
    vector<Interface*> getStuff();
private:
    vector<Foo*> stuff;
};

How do I implement the function getStuff()?


vector<Interface*> result(stuff.begin(), stuff.end());
return result;


std::vector<Inherited*> and std::vector<abstract*> are different, and pretty much unrelated, types. You cannot cast from one to the other. But you can std::copy or use iterator range constructor as @Grozz says.

Edit:

Answering your question in the comments: they are different the same way two classes with members of compatible types are different. Example:

struct Foo {
    char* ptr0;
};

struct Bar {
    char* ptr1;
};

Foo foo;
Bar bar = foo; // boom - compile error

For that last statement to work you'd need to define an explicit assignment operator like:

Bar& Bar::operator=( const Foo& foo ) {
    ptr1 = foo.ptr0;
    return *this;
}

Hope this makes it clear.


I am using this. It is not very nice, but fast I think :)

vector<Interface*> getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}

And you can also return only reference to the vector with this method

vector<Interface*> &getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜