A game engine has this class :
class MouseListener{
public :
MouseListener();
virtual void OnMouseDown(int mx,int my);
virtual void OnMouseUp(int mx,int my);
.
.
.
};
Each object that wants to listen to mouse input , have to inherent that class and override it's methods . To not have to declare a new type each time , the class is modified to :
class MouseListener{
public :
MouseListener();
std::function <void(MouseListener*,int,int)>OnMouseDown;
std::function <void(MouseListener*,int,int)>OnMouseUp;
.
.
.
};
now using the class can be done this way :
MouseListener * m = new MouseListener();
m->OnMouseDown = [](MouseListener * thiz,int x,int y){
//// do something
};
From the input system , only the functions of MouseListener that are not null ( assigned ) are called ( with thiz = the mouse listener ). knowing that the class is used from an external library ( static link ) , which is better in terms of performance ?
NOTE : None of those function will be called unless a mouse event is received , when that happens , the appropriate function is called for each object listening to mouse input ( not supposed to be lot , <50)
std::function
internally is implemented with virtual functions as well. Instead of retrieving your class vtable slot and doing an indirect call, the compiler has to extract the vtable from the pointer hidden into thestd::function
and do an indirect call over it. As an extra disadvantage,std::function
is a beast complicated enough that I've never seen the compiler do any devirtualization over it, when in many cases it is done on "regular" virtual functions. – Brachial