I am working on a C++ project. I need to put different classes into std::vector
. I found that this indeed is possible by creating classes with a common type and then putting pointers in the vector. In this case, I could cast the pointers to the type I need. That much is clear to me.
It is also mentioned that in principle it is possible to use not just pointers but smart pointers, i.e, std::vector<std::unique_ptr<TMyClass>>
. This is where my problem begins. TMyClass
has the indexing operator (operator[]
).
Let's say I have std::vector<std::unique_ptr<TMyClass>> A
. I try to access an element of the TMyClass
object like A[0][0]
or A[0].get()[0]
or (A[0])[0]
, but when I compile I get an error:
[bcc64 Error] type 'value_type' (aka 'std::unique_ptr<.....>') does not provide a subscript operator
How can I tell the compiler that the second index is related to the TMyClass
object and not to unique_ptr
? I would highly appreciate if somebody would explain to me how to access elements in this case.
You need to extract pointer first
A[0] //type: std::unique_ptr<TMyClass>&
Then extract object from that pointer (pointee)
*A[0] //type: TMyClass&
And then you can use your overloaded operators on this object
(*A[0])[0]