Skip to main content
GameDev.net gamedev.net
🔒 Locked

Function pointer and operator()?

Started by gautr Jul 12, 2006 at 8:23 AM 3 replies 650+ views
Original Post
gautr
gautr
Hi there. I'd like to be able to pass classes with operator() to a function which takes other functions as arguments. Can't get it right though :(

typedef void (*FuncPtr)();

void DoStuffWithFuncPtr(FuncPtr p)
{
	p();
}

void SomeFunc()
{
	// Implementation
}

class CSomeClass
{
public:
	CSomeClass() {}
	~CSomeClass() {}

	void operator()() { /* Implementation */ }
};

void main()
{
	CSomeClass instance;

	// Doesn't work!
	DoStuffWithFuncPtr(instance);
	// "error C2664: 'DoStuffWithFuncPtr' : cannot convert parameter 1 from 'CSomeClass' to 'FuncPtr'
    //  No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called"

	// This naturally works though
	DoStuffWithFuncPtr(SomeFunc);
}

Any thoughts on how to overcome this?
SiCrane
SiCrane
A class with an overloaded operator() is still a class and as such is not convertible to a function pointer type. You can create a template method that accepts both classes and function pointers such as:
template <typename Callable>void DoStuffWithFuncPtr(Callable p){	p();}

Alternately you can use something like boost::function to handle the abstraction between function pointers and function objects.
gautr
gautr
Thanks :)
gautr
gautr
Another question. How can I get the address operator() function in CSomeClass?
rip-off
rip-off
Quote:
Original post by gautr
Another question. How can I get the address operator() function in CSomeClass?


Member function pointers are not convertable to function pointers.

Typically a member function pointer will be bigger than the standard 32bit address on 32bit machines, as they have extra data in them.

But here you go anyway.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.