10

I have a simple RAII class to ensure some handle is properly disposed of. Now I would like to assert that no one is going to add by accident any virtual methods to it. The way I see it, I need to assert that the class does not have the vtbl pointer.

How can I do it? Is it possible to assert at the compile time?

EDIT

I will settle for desktop compilers. As far as I know there are no desktop c++ compilers that are not using vtbl for implementing polymorphism.

mark
  • 59,016
  • 79
  • 296
  • 580
  • Theoretically, You cannot do this in a portable way. – Alok Save Jan 10 '12 at 13:41
  • You may be interested in getting a _sealed_ class: http://stackoverflow.com/q/4712992/96780 – Daniel Daranas Jan 10 '12 at 13:42
  • 2
    The vtbl is an implementation detail. There might exist a compiler that doesn't use call tables to implement virtual functions. Do you want to restrict yourself to one specific compiler? – filmor Jan 10 '12 at 13:42
  • I'm not sure I understand what the danger of adding virtuals is? Surely if your handle is private, it is safe, no? – John McFarlane Jan 10 '12 at 14:43
  • Adding virtual changes the layout of the class, in some compilers the vtbl would be the first member of the class, whereas I need the handle to be the first member, for various reasons. – mark Jan 10 '12 at 15:03
  • @mark: You probably don't need that. Proper casts will adjust for that offset. I.e. if it's the first member of `class Foo`, then a cast to `Foo*` will take care of the necessary adjustments even if classed derived from `Foo` add a vtable. – MSalters Jan 10 '12 at 15:08
  • I know that. This is not the case. The case has to do with interop between C++ and C. – mark Jan 10 '12 at 18:50

1 Answers1

19

If you have a C++11 library, you can use std::is_polymorphic<T>:

If T is a polymorphic class (that is, a class that declares or inherits at least one virtual function), provides the member constant value equal true. For any other type, value is false.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    +1, nice! Also if you don't have C++11 and you have Visual C++ there's `__is_polymorphic` - http://msdn.microsoft.com/en-us/library/ms177194%28v=VS.90%29.aspx – sharptooth Jan 10 '12 at 13:44
  • Nice. I wish they introduced more static type info / reflection features in C++11 (like a way to obtain a list of fields/methods for a class). This would make it so much easier to create some meta-code like wrappers for scripting languages. – Kos Jan 10 '12 at 13:46
  • Boost.TypeTraits also has this, btw. – jrok Jan 10 '12 at 13:54
  • +1: Have a badge. Worth noting that we can completely ignore the implementation concept of "vtables" here, and just focus on the class being polymorphic with virtual functions. – Lightness Races in Orbit Jan 10 '12 at 13:56
  • I guess no compile time assertion is possible for this case, right? – mark Jan 10 '12 at 13:56