1

Imagine I have a class called Test and inside this class I have a list of pointers which their types are all from class Base. Although any pointer which is stored in list is pointer to an object from classes which are derived from class Base. I want to provide a getter() function for a specific derived type which returns the object of specific class. Note that we don't know the index of required pointer inside class.

class Base
{
    /// Base class do have a pure virtual function
};

class Derived1
{
};

class Derived2
{
};


Class Test
{
    std::vector<Base*> pointers; /// any STL collection... vector may be more frequent

     get_derived1_object(); /// 
};

I think of some possible implementations of get_derived1_object() like this (And in my opinion both have some problems):

1- storing a copy pointer of Derived1's object's pointer inside class. In case I want to try using unique_pre it is not a good solution.

2- iterate over pointers in order to find which item is from Derived1 class using runtime type checking. (for example trying to use dynamic_cast or sth similar). In my usecase, using runtime type checking is better not to be used.

P.S: having multiple items of each class is not important here because I'm sure I don't have 2 different pointers from same class inside my list and consider it taken care of.

I was wondering if I could find the best solution for providing a function like get_derived1_object (whether from my own given solutions or sth else).

rezaebrh
  • 424
  • 2
  • 6
  • 19
  • 2
    FYI: [Mapping Types to Values (in C++)](https://gpfault.net/posts/mapping-types-to-values.txt.html) – Scheff's Cat Dec 18 '19 at 17:04
  • 1
    FYI: [SO: Use data type (class type) as key in a map](https://stackoverflow.com/q/9859390/7478597) – Scheff's Cat Dec 18 '19 at 17:06
  • 3
    Needing to know the type of a `Base*` would normally be considered a code smell. It would be easier to give a good answer if you could provide some more details on **why** you need this and **how** it will be used. – super Dec 18 '19 at 17:06
  • 1
    this may be useful: https://stackoverflow.com/questions/59365859/should-how-can-i-avoid-downcasting-in-this-case – Michael Kenzel Dec 18 '19 at 17:13

1 Answers1

1

Instead of a vector, use an associative map of std::type_index to base pointer. Ensure that only matching type index is used, and then you don't need dynamic_cast, because we know that the type will match the mapped pointer. That said, use of std::type_index still relies on RTTI. No linear searching is needed.

eerorika
  • 232,697
  • 12
  • 197
  • 326