سؤال

Subscribing to events in C++/CX goes something like this:

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

All documentation I've found for how to subscribe to events in WRL shows examples using lambda expressions, like this:

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

But how can I subscribe to an event in WRL and provide a class method instead of a lambda? Something like this:

hr = listener->add_ConnectionReceived(&MyClass::OnConnectionReceived, &this->connectionReceivedToken);
هل كانت مفيدة؟

المحلول

I'm not familiar with WRL but since it supports C++11 lambdas I believe it should also support 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);

نصائح أخرى

There is an overload of Callback that takes this + member function. here it is...

ComPtr<typename Details::DelegateArgTraitsHelper<TDelegateInterface>::Interface> Callback(_In_ TCallbackObject *object, _In_ HRESULT(TCallbackObject::* method)(TArgs...)) throw()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top