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

前端 未结 2 704
Happy的楠姐
Happy的楠姐 2021-01-22 07:18

I can pass in a Child to a member function expecting a Parent, however when using vectors I get a compile error saying there\'s no matching declaration. See the CorrelationEngin

相关标签:
2条回答
  • 2021-01-22 08:01

    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.

    0 讨论(0)
  • 2021-01-22 08:09

    The function could be changed to a template function:

    template< typename T >
    std::vector<std::string> getUniqueLabels(std::vector<T> events);
    
    0 讨论(0)
提交回复
热议问题