Differences between method pointer casting rules in g++ and Visual Studio
struct Test
{
typedef unsigned (Test::*MethodPtr)();
unsigned testMethod() {}
};
typedef void (*ThreadPtr)(void *);
ThreadPtr threadPtr = reinterpret_cast<ThreadPtr>(&Test::testMethod);
I want to launch a thread into a class method of a particular object. I use a method pointer as the thread entry point and pass the object pointer as the only parameter. This works as I don't have any virtual declarations in my structure.
My question relates to the reinterpret_cast operation. g++ allows this, Visual Studio 2008 does not. I got around the VS2008 restrictions by memc开发者_Python百科pying the method pointer value directly into the threadPtr variable. The resulting code worked ok but it's a gruesome workaround for what should be a simple operation. Can anyone provide more elegant alternatives?
Thanks
-G
Edit :
Just to clarify, the warning given by gcc is as follows:
methodPtrTest.cpp:14: warning: converting from ‘void (Test::*)()’ to ‘void (*)(void*)’
Okay, do this:
void threadMethod(void* ptr) {
static_cast<Test*>(ptr)->testMethod();
}
ThreadPtr threadPtr = &threadMethod;
That way, you're dealing with a real function, not a PMF.
精彩评论