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

Click For Summary
SUMMARY

The discussion centers on the compiler error encountered when passing a std::vector to a function expecting a std::vector, where T2 is derived from T1. The consensus is that this approach will not compile due to type safety rules in C++. A vector of actual instances cannot be implicitly converted, unlike vectors of pointers or references. To resolve this, one must pass a pointer to the vector and ensure that the vector elements are of the same type.

PREREQUISITES
  • Understanding of C++ inheritance and polymorphism
  • Familiarity with std::vector and its usage
  • Knowledge of C++ type safety and compiler behavior
  • Experience with function parameter passing in C++
NEXT STEPS
  • Research C++ inheritance rules and their implications on type conversion
  • Learn about std::vector of pointers and references in C++
  • Explore C++ function overloading and template specialization
  • Study the differences between passing by value and passing by pointer/reference in C++
USEFUL FOR

C++ developers, software engineers dealing with object-oriented programming, and anyone troubleshooting type-related compiler errors in C++.

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.
 

Similar threads

  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 12 ·
Replies
12
Views
4K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K