C/C++ Compiler Error: Passing std::vector<T2> to Function Taking std::vector<T1>

AI Thread Summary
When passing a std::vector<T2> to a function expecting std::vector<T1>, where T2 is derived from T1, the compiler raises an error because std::vector is not covariant. This means that a vector of derived types cannot be treated as a vector of base types directly. While using pointers or references might allow for polymorphic behavior, actual instances in vectors do not support this due to their strict type requirements. To achieve the desired functionality, one must pass a pointer to the vector and ensure that the vector elements are of the same type.
ehrenfest
Messages
2,001
Reaction score
1
If I have a function that takes a std::vector< T1 > and I pass it a std::vector< T2 >, where T2 is publicly derived from T1, that should work, why does my compiler complain?
 
Technology news on Phys.org
What makes you think that should work? A vector of references or pointers might work; note well that I am not saying it will. A vector of actual instances is a different beast. I would think that this should not work.
 
You have to pass a pointer to the vector, and make sure the vector elements are the same.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Replies
22
Views
3K
Replies
8
Views
2K
Replies
39
Views
4K
Replies
1
Views
1K
Back
Top