C++ static virtual members?


Is it possible in C++ to have a member function that is both static and virtual? Apparently, there isn't a straightforward way to do it (static virtual member(); is a compile error), but is there at least a way to achieve the same effect?


struct Object
     struct TypeInformation;

     static virtual const TypeInformation &GetTypeInformation() const;

struct SomeObject : public Object
     static virtual const TypeInformation &GetTypeInformation() const;

It makes sense to use GetTypeInformation() both on an instance (object->GetTypeInformation()) and on a class (SomeObject::GetTypeInformation()), which can be useful for comparisons and vital for templates.

The only ways I can think of involves writing two functions / a function and a constant, per class, or use macros.

Any other solutions?

10/2/2015 10:03:31 PM

No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()? It can't know which derived class version to call since there's no object associated with it.

You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.

11/30/2009 3:30:23 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow