Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function pointers and classes

Say I have:

void Render(void(*Call)())
{
    D3dDevice->BeginScene();
    Call();
    D3dDevice->EndScene();
    D3dDevice->Present(0,0,0,0);
}

This is fine as long as the function I want to use to render is a function or a static member function:

Render(MainMenuRender);
Render(MainMenu::Render);

However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.

Render(MainMenu->Render);

However I really have no idea how to do this, and still allow functions and static member functions to be used.

like image 670
Fire Lancer Avatar asked Sep 13 '08 12:09

Fire Lancer


People also ask

What are function pointers in C?

Function pointers in C can be used to create function calls to which they point. This allows programmers to pass them to functions as arguments. Such functions passed as an argument to other functions are also called callback functions.

Can we use pointers for functions C?

In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.

How do you call a function from a pointer object?

Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);

What is the difference between a function and a pointer?

Function Pointers are pointers(like variable pointers) which point to the address of a function. They actually calling the underlying function when you dereference them like a function call does. The main advantage of a function pointer is that you can pass it to another function as a parameter for example ...


2 Answers

There are a lot of ways to skin this cat, including templates. My favorite is Boost.function as I've found it to be the most flexible in the long run. Also read up on Boost.bind for binding to member functions as well as many other tricks.

It would look like this:

#include <boost/bind.hpp>
#include <boost/function.hpp>

void Render(boost::function0<void> Call)
{
    // as before...
}

Render(boost::bind(&MainMenu::Render, myMainMenuInstance));
like image 172
David Joyner Avatar answered Oct 23 '22 17:10

David Joyner


You can make a wrapper function void Wrap(T *t) that just calls t->Call() and have Render take such a function together with an object. That is:

void Wrap(T *t)
{
  t->Call();
}

void Render(void (*f)(T *), T *t)
{
  ...
  f(t);
  ...
}
like image 40
mweerden Avatar answered Oct 23 '22 18:10

mweerden