开发者

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

开发者 https://www.devze.com 2023-01-19 11:13 出处:网络
class Interface{}; class Foo: public Interface{}; class Bar{ public:开发者_开发技巧 vector<Interface*> getStuff();
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

精彩评论

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