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 printsAnObject 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.
For completeness sake, here's the answer my buddy just sent me. From the look of it, it's probably similar to how TR1 does it (though I haven't looked at the code myself).
template<class T>
class HasVTable
{
public :
class Derived : public T
{
virtual void _force_the_vtable(){}
};
enum { Value = (sizeof(T) == sizeof(Derived)) };
};
#define OBJECT_HAS_VTABLE(type) HasVTable<type>::Value