简体   繁体   中英

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?

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 */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM