pointer to function - pointer to member function

Started by
7 comments, last by Endar 18 years, 5 months ago
Just for fun, I'm trying to convert a pointer to a member function to a pointer to a non-member function.

class A
{
public:
	int s;

	A():s(5)
	{	}

	void func()
	{
		std::cout << s << std::endl;
	}
};

int main()
{
	void (*f)(A*);

	A a;

	f = (void (__cdecl*)(A*)) A::func;

return 0;
}

I got to this point, and, it doesn't work:

error C2440: 'type cast' : cannot convert from '' to 'void (__cdecl *)(class A *)'
And I'm not sure what to try now.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
Advertisement
Perhaps reinterpret_cast would come in handy at this point.

CM
Don't bother. Pointers to member functions have a very different structure than normal pointers to functions. Pointer to member functions can be up to four times the size of a pointer to a normal function, so trying to stuff it in will lose data.
Really? What's the structure difference?
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
Here's a pretty good overview of the subject: Member Function Pointers and the Fastest Possible C++ Delegates
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
As I understand it, taking the address of a class method may or may not actually point to the address of the function. It could, instead, point to...something else, I assume =).

Read the C++ FAQ Lite, it explains much better than I. Click here for the best warning label.

EDIT: Also, I noticed that in your original example you're trying to use the __cdecl calling convention -- if this was in C, that would be closer to the "correct" solution, though, as above, it may or may not point to what you actually want. In C, methods and function pointers are different because of calling convention; in C++, they're different because of the way they're represented (having a really hard time expressing this, considering I don't fully understand it).
Things change.
Well, thanks guys, you learn something new every day.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
It's not exactly what you're trying to do, but have you considered using
boost::function and boost::bind? That will give you some functors that are a whole lot like function pointers.
 ~~C--O   -
Thanks, but I wasn't really trying to do anything. It's just one of those things where you sit up and say "I wonder if that is possible?".
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper

This topic is closed to new replies.

Advertisement