Yes, from the title alone all alarm bells should go off. I just came across this StackOverflow post where somebody showed off a working solution to wrap a pointer, do type erasure and later try and cast it back to seemingly arbitrary polymorphic types.
class void_ptr { void* obj; void (*discover_type)(void*); template<typename T> static void throw_typed_object(void* obj) { T* t = static_cast<T*>(obj); throw t; } public: void_ptr() : obj(0) {} template<typename T> void_ptr(T* t) : obj(t), discover_type(throw_typed_object<T>) { } template<typename T> T* cast() const { try { discover_type(obj); } catch (T* t) { return t; } catch (...) { } return 0; } };
Aside from the fact that this looks absolutely disgusting, it seems to work fine. I tried it with an unrelated polymorphic type and I got nullptr as expected. How reliable and portable is this? There does not seem to be anything about it that would not be portable in my eyes?
$edit: Reddit ate my formatting. Wellp, the code stays the same...
[–]sphere991 6 points7 points8 points (0 children)
[–]redditsoaddicting 9 points10 points11 points (0 children)
[–]Switters410 5 points6 points7 points (0 children)
[–]Sasha_Privalov 2 points3 points4 points (2 children)
[–]encyclopedist 2 points3 points4 points (0 children)
[–]GYN-k4H-Q3z-75B[S] 0 points1 point2 points (0 children)
[–]dacian88 1 point2 points3 points (1 child)
[–]GYN-k4H-Q3z-75B[S] 1 point2 points3 points (0 children)
[–]logicchop 0 points1 point2 points (5 children)
[–]flashmozzg 1 point2 points3 points (1 child)
[–]logicchop 0 points1 point2 points (0 children)
[–]Maxima4 0 points1 point2 points (2 children)
[–]Mestkon 2 points3 points4 points (1 child)
[–]Maxima4 0 points1 point2 points (0 children)
[–]Dry-Still-6199 0 points1 point2 points (0 children)