KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
A friend of mine sent me the following challenge earlier today: Given the following code, propose an implementation of OBJECT_HAS_VTABLE so the program prints AnObject has a vtable = 0, AnObjectWithVTable has a vtable = 1 . class AnObject { int m_a; void DoSomething() {} public: AnObject() {m_a = 0;} }; class AnObjectWithVTable { int m_b; virtual void DoStuff() { } public: AnObjectWithVTable() {m_b = 0;} }; void main() { printf("AnObject has a vtable = %i, AnObjectWithVTable has a vtable = %i\n", OBJECT_HAS_VTABLE(AnObject), OBJECT_HAS_VTABLE(AnObjectWithVTable)); } I've came up with the following solution which I think is decent enough: template <typename T> bool objectHasVtable() { class __derived : public T {}; T t; __derived d; void *vptrT=*((void **)&t); void *vptrDerived=*((void **)&d); return vptrT != vptrDerived; } #define OBJECT_HAS_VTABLE(T) objectHasVtable<T>() Is there a better solution to this problem? Edit The solution doesn't have to be generic across all compilers. It can work on gcc, g++, MSVC... Just specify for which compiler your solution is known to be valid. Mine is for MSVC 2010.
Tags (comma-separated)
Save Edits
Cancel