This question already has an answer here:
I have two structs that had methods in common, that are defined in an Interface (I can't change these):
struct Interface {
virtual int Foo() = 0;
};
struct A : Interface {
virtual int Foo() override;
//A specific methods etc
};
struct B : Interface {
virtual int Foo() override;
//B specific methods etc
};
If there's a function that needs to take an Interface then it's pretty simple: //a member variable std::vector m_as;
int DoubleFoo( Interface& obj ) {
return obj.Foo() * 2;
}
DoubleFoo(m_as[0]);
However if there's a function that needs multiple Interface then it's not so simple:
int SumFoo( std::vector<Interface>& objs ) {
int sum = 0;
for (auto&& obj : objs ) {
sum += obj.Foo();
}
return sum;
}
because if I have an existing (eg member) variable of std::vector<A> I can't simply do:
SumFoo(m_as);
Instead I have to either change SumFoo to std::vector<Interface*> and have to create a new vector of pointers that point to the elements in the original array.
Or just cast it in the function call, which is quite ugly:
SumFoo((std::vector<Interface>&)m_as);
How is it possible to easily/nicely use interfaces in C++, when it comes to something as simple as needing a vector of them?
I understand why I can't pass a subclass to a function expecting it's base class by value because of object slicing etc. But why isn't the cast from std::vector<Derived>* to std::vector<Base>* implicit, when Derived* to Base* is?
Aucun commentaire:
Enregistrer un commentaire