WRT callback
之前写了一个函数,用WRT里面的callback函数,今天一更新WDK,发现callback一直报错。
这句话是定位到
return Callback<TDelegateInterface>([=](Auto&& ...args) { return ((*object).*(method))(args ...); });
先撇开Auto&&,看Auto,把上面的语句中,&&去掉,发现也是同样的error,问题就出在函数的形参不能是Auto类型的。这个貌似除了改WDK也没有别的办法了。应该是微软的bug吧?
所以,采用如下的callback函数
/ Construct a COM/WinRT delegate (an object with an Invoke() method) from a lambda.
// Check the return from this function for null to detect out of memory (E_OUTOFMEMORY) failure case.
template<typename TDelegateInterface, typename TLambda>
ComPtr<typename Details::ArgTraitsHelper<TDelegateInterface>::Interface> Callback(TLambda&& callback) throw()
{
static_assert(__is_base_of(IUnknown, TDelegateInterface) && !__is_base_of(IInspectable, TDelegateInterface), "Delegates objects must be 'IUnknown' base and not 'IInspectable'");
return Make<Details::InvokeHelper<TDelegateInterface, TLambda, Details::ArgTraitsHelper<TDelegateInterface>::args>>(Details::Forward<TLambda>(callback));
}
使用了Lambda匿名函数。
例子如event.c中所示
====================================================================
Microsoft::WRL::ComPtr<DeferrableEventArgs> lifetime(this);
auto callback = Microsoft::WRL::Callback< ::ABI::Windows::Foundation::IDeferralCompletedHandler >(
[lifetime]() { return lifetime->Complete(); });
====================================================================
所以,下面简单介绍一下lambda函数
void abssort(float* x, unsigned n) {
std::sort(x, x + n,
// Lambda expression begins
[](float a, float b) {
return (std::abs(a) < std::abs(b));
} // end of lambda expression
);
} 红色部分就是lambda函数啦,主要由6个部分组成
-
capture clause (Also known as the lambda-introducer in the C++ specification.) 第一部分是[]这个符号构成,也叫做capture子句。在这个子句中,可以写作[&][=],有不同的意思,&表示是引用,=表示取值。通常的写法是把所有需要用到的参数(除了lambda函数中的形参)写在里面,如this指针等等
-
parameter list Optional. (Also known as the lambda declarator) 第二部分是函数的形参,例子中有用auto的,不知道为什么编译不过?
auto y = [] (auto first, auto second) { return first + second; };
-
mutable specification Optional.
-
exception-specification Optional.
-
trailing-return-type Optional.返回值
-
lambda body)函数体
Reference:
https://msdn.microsoft.com/en-us/library/dd293608.aspx
https://msdn.microsoft.com/en-us/library/dd293599.aspx lambda的例子