How to determine if a C++ class has a vtable?
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.
The standard method is to use std::is_polymorphic
from C++11/C++03 TR1/Boost to determine if a class (and its bases) contain any virtual members.
#include <type_traits>
#define OBJECT_HAS_VTABLE(T) (std::is_polymorphic<T>::value)
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
You can use the following properties of C++:
dynamic_cast
fails at compile time if the argument is not a polymorphic class. Such a failure can be used with SFINAE.dynamic_cast<void*>
is a valid cast that returns the address of the complete polymorpic object.
Hence, in C++11:
#include <iostream>
#include <type_traits>
template<class T>
auto is_polymorphic2_test(T* p) -> decltype(dynamic_cast<void*>(p), std::true_type{});
template<class T>
auto is_polymorphic2_test(...) -> std::false_type;
template<class T>
using is_polymorphic2 = decltype(is_polymorphic2_test<T>(static_cast<T*>(0)));
struct A {};
struct B { virtual ~B(); };
int main() {
std::cout << is_polymorphic2<A>::value << '\n'; // Outputs 0.
std::cout << is_polymorphic2<B>::value << '\n'; // Outputs 1.
}
精彩评论