Static Virtual functions in c++

末鹿安然 提交于 2019-12-03 11:07:51

The ATL framework gets around the limitation of no virtual statics by making the base class be a template, and then having derived classes pass their class type as a template parameter. The base class can then call derived class statics when needed, eg:

template< class DerivedType >
class Base
{
public:
  static void DoSomething() { DerivedType::DoSomethingElse(); }
};

class Derived1 : public Base<Derived1>
{
public:
  static void DoSomethingElse() { ... }
};

class Derived2 : public Base<Derived2>
{
public:
  static void DoSomethingElse() { ... }
};

This is known as Curiously recurring template pattern, which can be used to implement static polymorphism.

Do you mean you need a pointer to a static function (e.g. to pass as an argument to another function that requires a pointer to a static function), but you need to access that function pointer virtually? In that case, use a virtual function to get the function pointer:

typedef void (*function)();
void do_stuff_with_function(function);

struct Base {
    virtual ~Base() {}
    virtual function get_function() = 0;
};

struct Derived : Base {
    function get_function() {return my_function;}
    static void my_function();
};

Derived d;
do_stuff_with_function(d.get_function());

static function can not be virtual since they do not have an instance through which they are accessed. I do believe you can overwrite them though.

You can't have static virtual functions in C++.

Virtual functions typically rely on this pointer to determine the type of function to be called at run time.

A static member function does not pass a this so static virtual functions are not allowed in C++.

If i am correct in understanding ur question, then u can follow the following approach otherwise ignore..

have static function pointer in the base class.

in base class have a static function ( in which u call the function by using that static function pointer)..

in derived classes set that static function poiter to the function defination u wish to execute.. ( in base class u can set the function pointer to some default function).

You cannot have static virtual functions, because it doesn't make sense to have them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!