Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Virtual functions in c++

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?

like image 575
fank Avatar asked Jun 09 '11 10:06

fank


People also ask

Can a virtual function be static?

A virtual function cannot be global or static because, by definition, a virtual function is a member function of a base class and relies on a specific object to determine which implementation of the function is called.

What is a static method virtual?

The Virtual Static Idiom is a very simple technique used in C++ to make static methods virtual. This way, static methods can be overridden by subclasses. Actually, it just binds a static (class) method to an instance by explicitly passing the this pointer.

What is static function in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

What are static functions?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.


1 Answers

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.

like image 200
Remy Lebeau Avatar answered Sep 19 '22 17:09

Remy Lebeau