Static Virtual functions in c++

fank picture fank · Jun 9, 2011 · Viewed 9k times · Source

I have a base class and a derived one and I want to change base functions while keeping them static as they should be passed to other functions as static.

How can I do that?

Answer

Remy Lebeau picture Remy Lebeau · Jun 10, 2011

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.