I want to use the thunk function template to pass it around to pthread_create and stuff like that.
I would expect the compiler to instantiate the function with the given parameters, all the info is there, and then use the typedef as a function ptr to pass to those functions.
#include <string>
class ServerImpl{
public:
ServerImpl(std::string host, int port);
void run();
};
template<typename T,void (T::*mem_fn)()>
void *thunk(void *obj) {
(static_cast<T*>(obj)->*mem_fn)();
return 0;
}
typedef void *(*Function) (void);
Function fun = (Function)&thunk<ServerImpl,&ServerImpl::run>;
fun();
JUST CHANGED IT
See, with this I get a linker error, which is what it brought me to the previous one. Omit the fact that I should be passing an object.
Server.o: In function `ServerImpl::ServerImpl(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)':
Server.cpp:(.text+0x11f): undefined reference to `void* thunk<ServerImpl, &(ServerImpl::run())>(void*)'
thunkis a function template. How can you usetypedefon it? It doesn’t make sense. It is not a type. You can applytypedefonly on types.You should do this:
Your arguments to
pthread_createare wrong. It takes 4 arguments, not 2.Why did I use new?
I created an instance of
ServerImplusingnew, because the instance has to exist even if the function in which you created the thread have returned. If I don’t create the instance usingnew, and instead use local variable, then the code invoke undefined behavior, if the function returned but the thread continue running.Reply to your edit:
This is wrong. Because
thunktakes one argument. So you should be doing this instead:The member function
runis invoked on this argument which you passed.