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?

IE:

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?


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.


Many say it is not possible, I would go one step further and say it is not meaningfull.

A static member is something that does not relate to any instance, only to the class.

A virtual member is something that does not relate directly to any class, only to an instance.

So a static virtual member would be something that does not relate to any instance or any class.


I ran into this problem the other day: I had some classes full of static methods but I wanted to use inheritance and virtual methods and reduce code repetition. My solution was:

Instead of using static methods, use a singleton with virtual methods.

In other words, each class should contain a static method that you call to get a pointer to a single, shared instance of the class. You can make the true constructors private or protected so that outside code can't misuse it by creating additional instances.

In practice, using a singleton is a lot like using static methods except that you can take advantage of inheritance and virtual methods.

链接地址: http://www.djcxy.com/p/54150.html

上一篇: 如果我重写它,我可以调用基类的虚函数吗?

下一篇: C ++静态虚拟成员?