我有这个助手类,我用它来调用需要静态 C 函数的代码的成员方法。这个特定的“版本”与 Windows LPTHREADROUTINE 回调兼容,将DWORD (class::method) (void *)
函数作为参数,调用如下:
CreateThread(NULL, 0, runThreadFunction<SomeClass>, makeThreadInfo(&myClass, &SomeClass::ThreadFunction, NULL), 0, NULL);
我希望使整个事情变得通用,并且我知道它可以使用新的 C++11 标准来完成,但我无法完成它。
#pragma once
#include <stdafx.h>
template <typename C>
struct ThreadInfo
{
// we have an object
C* obj;
// and that object has a function that takes void* and returns DWORD, and so is suitable for a threadproc (except for it being a member function)
DWORD (C::* function)(void*);
// and we have any amount of extra data that we might need.
void* data;
// default copy c-tor, d-tor and operator= are fine
ThreadInfo(C* o, DWORD (C::*func)(void*), void* d) : obj(o), function(func), data(d)
{
}
};
template <typename C>
DWORD WINAPI RunThreadFunction(void* data)
{
shared_ptr<ThreadInfo<C> > ti((ThreadInfo<C>*)data);
//ThreadInfo<C>* ti = (ThreadInfo<C>*) data;
return ((ti->obj)->*(ti->function))(ti->data);
}
template <typename C>
void* MakeThreadInfo(C* o, DWORD (C::* f)(void*), void* d)
{
return (void*)new ThreadInfo<C>(o, f, d);
}
我尝试将 MakeThreadInfo 函数的接口更改为如下所示:
template <typename C, typename R, typename... P>
void* MakeThreadInfo(C* o, std::function<R(P&...)> f, void* d)
这似乎是要走的路,但我无法将这个值传递给上游。
这就是我想要得到的:
给定一个带有 MyMethod 方法的类 MyClass,以及一个变量返回类型的回调和一个或多个不同类型的参数(最后一个是 a void *userData
),我怎样才能在尽可能少的样板化的情况下将一些东西传递给回调和让它依次调用 MyClass::MyMethod。
为了显示:
typedef bool (*Callback1)(void *userData);
typedef int (*Callback2)(bool param, void *userData);
void TheirLibrary::Function1(Callback1 callback, void *userData);
void TheirLibrary::Function2(Callback2 callback, void *userData);
class MyClass
{
bool MyMethod1(void *userData);
int MyMethod2(bool someParam, void *userData);
void DoSomething()
{
Function1(CreateGenericCPointer(&MyClass::MyMethod1), &MyClass);
Function2(CreateGenericCPointer(&MyClass::MyMethod2), &MyClass);
}
}
什么是有效的实现CreateGenericCPointer
?