我需要将 Lambda 作为回调传递(特别是对于 WinAPI)。思路如下:
将 lambda 存储在一个单例类中(每个 Lambda,也有两个相同的,具有不同的类型),所以它应该是安全的
LambdaSingleton<Lambda_Type>::instance = l;
将调用 lambda 实例的静态方法的地址作为回调传递。
template < typename Lambda, typename Callback_Signature_R, typename... Callback_Signature_Args> struct LambdaCallbackSupport{ /** * Callback method * * @param args * The parameters to feed to the lambda * @return * The return value of the execution of the lambda */ static Callback_Signature_R __stdcall callback(Callback_Signature_Args... args){ return LambdaSingleton<Lambda>::instance(args); } };
我已经有一个工作类,用于在编译时提取有关函数的信息:
template<
typename C,
typename R,
typename... Args>
struct Traits<R(__stdcall *)(Args...) const>{
//various typedefs for R, tuple of args, arity etc..
};
所以我会得到这样的东西:
//Example lambda
int toBeCaptured = 8;
auto lambda =
[&](std::string& str) -> size_t{
return toBeCaptured + str.length();
};
typedef decltype(lambda) Lambda;
//Expected callback signature
typedef size_t(__stdcall *CallbackSignature)(std::string&);
//Configure a callback support and pass its method
typedef Traits<CallbackSignature> callbackTraits;
typedef LambdaCallbackSupport<
Lambda,
callbackTraits::Result_Type,
callbackTraits::Args_Tuple_Pack> CallbackSupportType;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //How to unpack the tuple without actually have the arguments??
//Store the lambda instance statically
Singleton<Lambda>::instance = lambda;
//Pass the callback
void* pFunc = &CallbackSupportType::callback;
//Simulate invocation of callback
std::string str("may work?");
size_t ret = (*pFunc)(str);
由于我只需要让编译器生成一个回调类专业化(而不是实际调用它的方法),我如何应用本网站其他问题中提出的迭代解包技术?
谢谢