Search code examples
c++typesrtti

how to get typeid of incomplete type c++


I need to store pointers in such a way that later I'll be able to restore it's original type and do some stuff.

vector<pair<void*, type_info>> pointers;

and later

for(auto p : pointers){
   switch(p.second)
      case typeid(sometype):
         DoStuff((sometype*)p.first);
      break; //and so on...
}

When I add pointer I naturally do this

SomeType* pointer;

pointers.emplace_back((void*)pointer, typeid(SomeType));

And it works fine until type is incomplete. typeid is not working with incomplete types so I cannot use it with (for example) SDL_Texture from SDL2 library. But I need somehow differ different types from each other even if part of them is incomplete ones. What to do?


Solution

  • Use std::any.

    Some examples for your case:

    #include <vector>
    #include <any>
    
    std::vector<std::any> pointers;
    SomeType *pointer;
    pointers.emplace_back(std::make_any<SomeType*>(pointer));
    
    /* later on */
    for (auto p : pointers) {
        if (SomeType *t = std::any_cast<SomeType*>(p))
            /* p is of type SomeType* */
        else if (...)
            /* check other types */
    }