2013-10-03 18 views
0

訂閱在C事件++/CX是這樣的:WRL:如何訂閱事件*不使用lambdas?

listener::ConnectionReceived += 
ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MyClass::OnConnectionReceived); 

所有文件我已經找到了如何訂閱在WRL事件顯示的例子使用lambda表達式,像這樣:

auto connectionReceivedHandler = Callback<ITypedEventHandler<StreamSocketListener*, StreamSocketListenerConnectionReceivedEventArgs*>> 
([&] (IStreamSocketListener* cbListener, IStreamSocketListenerConnectionReceivedEventArgs* args) 
{ 
    this->doSomething(); 
}); 
hr = listener->add_ConnectionReceived(connectionReceivedHandler.Get(), &this->connectionReceivedToken); 

但是我如何訂閱WRL中的事件並提供類方法而不是lambda?事情是這樣的:

hr = listener->add_ConnectionReceived(&MyClass::OnConnectionReceived, &this->connectionReceivedToken); 

回答

1

我不熟悉WRL但因爲它支持C++ 11 lambda表達式,我相信它也應該支持std::bind

auto callback = Callback<ITypedEventHandler<StreamSocketListener*, 
             StreamSocketListenerConnectionReceivedEventArgs*>> 
    (std::bind(
    &MyClass::OnConnectionReceived, 
    ptr_to_instance_of_MyClass, // eg. this 
    std::placeholders::_1,  // cbListener 
    std::placeholders::_2  // args 
)); 

hr = listener->add_ConnectionReceived(callback.Get(), &this->connectionReceivedToken); 
+0

當我嘗試訪問我的回調中的類成員時出現訪問衝突錯誤,但這是單獨發佈的另一個問題。這回答我的問題,謝謝! – Robert

+0

@Robert訪問類成員的Segfault可能意味着'ptr_to_instance_of_MyClass'是懸而未決的。你有沒有和lambda一樣的問題?如果是這樣,請檢查MyClass實例的生命週期。 – syam

0

有回調的重載需要這個+成員函數。這裏是...

ComPtr<typename Details::DelegateArgTraitsHelper<TDelegateInterface>::Interface> Callback(_In_ TCallbackObject *object, _In_ HRESULT(TCallbackObject::* method)(TArgs...)) throw() 
+0

專業提示:用4個空格前置(每行代碼)以正確格式化爲代碼塊。 – HolyBlackCat

+0

感謝您的提示。 –