• Advertisement
Sign in to follow this  

Passing Function as argument

This topic is 3319 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello I am trying to pass a function as an argument but I don't understand how to do it could someone help me out? This is the header with the function prototype.
#ifndef LOOP_H
#define LOOP_H

#include "input.h"

void main_loop(Input, bool(*)());

#endif


This is the function
bool Application::handle_messages()
{
	static MSG msg;

	if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		if(msg.message == WM_QUIT)
			return FALSE;

		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return TRUE;
}


This is the function call
main_loop(application.get_input_data(), application.handle_messages);


This is the function definition
#include "loop.h"
#include "winmain.h"
#include "input.h"
#include <vector>

void main_loop(Input input_data, bool (*handle_messages)())
{
//	std::vector<object> game_objects;
//	init_game(&game_objects);

	while((*handle_messages)())
	{
//		update(&game_objects, input_data);
//		render(&game_objects);
	}
}


Share this post


Link to post
Share on other sites
Advertisement
Yikes that's a lot of material, I have to read it all to know how solve this problem :S?

Share this post


Link to post
Share on other sites
Short version : C++ does not have built-in closures.

Long version : C++ functions are just code. They don't carry associated data or objects. So, when you pass "application.handle_messages", you can only pass the code associated to that function, not the "application" object. Since you can't run "handle_messages" without an object, and the object cannot be carried along with it, the program doesn't compile. The typical solution is to use a closure-like type, such as boost::function, or a template-based functor approach.

Share this post


Link to post
Share on other sites
<evangelism>You could move on to a functional language like Objective Caml, which allows things like that and many more.</evangelism>

Ideally, you'd download boost and just:

void main_loop(Input,boost::function<bool()>);

boost::function<bool()> handle_messages =
boost::bind(&Application::handle_messages, application);
main_loop(input,handle_messages);


If you're too lazy to install boost (it's a mere "apt-get install libboost" away on my computer, for instance), you can always use an old-fashioned way using templates:

template<typename F>
void main_loop(Input in, F f)
{
// Put the code for the main loop here.
}

namespace
{
struct closure
{
Application &app;
bool operator() () { return app.handle_messages(); }
};
}

::closure handle_messages = { application };
main_loop(input,messages);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement