How to pass a vector of a Child class in to a function expecting a vector of Parent class?

拜拜、爱过 提交于 2019-12-01 23:42:52

This is not possible in C++, this requires a feature called covariance.

Even if type A is a subclass of type B, type X<A> is completely unrelated to type X<B>

Thus you cannot pass std::vector<UPSEvent> to a function expecting std::vector<Event>, since they are unrelated types. Even pass by reference/pointer will not work.

There are two ways to get around this.

One would be to make both vectors hold pointers to Event, then they would have identical types.

The other, would be to make the function a template function, as Daniel suggests.

You would need to fix the signature as well, as billz points out.

The function could be changed to a template function:

template< typename T >
std::vector<std::string> getUniqueLabels(std::vector<T> events);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!