Sunday 15 March 2015

c++ - Passing and storing lambda function as callbacks -


I was thinking that this would be an acceptable approach to writing callback:

collecting callback :

  straight event holder {std :: function & lt; Void () & gt; call back; EventTypes :: EventType type; }; Std :: vector & lt; Events: EventHolder & gt; EventCallbacks;   

method definition:

  at zero (EventType OnEventType, std :: function  & amp; amp; and callback ) {Event :: Eventholler NewEvent; NewEvent.Callback = std :: move (callback); NewEvent.Type = OnEventType; EventCallbacks.push_back (std :: move (NewEvent)); }   

Binding event:

  button-> (Event type :: click, [] {// ... callback body});   

My biggest question will be about passing through the callback value. Is this a legitimate approach?

This event is a perfectly valid approach to storing handlers.

However, I tell some details about the signature of your function to add callback. You pass it by making a reference from the context. In your example, you currently have:

  at zero (EventType OnEventType, std :: function & lt; void () & gt; & amp; amp; and callback)   

It is good, unless you only tie it for attitude. However, unless you want to reject it for certain reasons, then I suggest that you always have a method that accepts criteria from the value or the lavalu context and is considered necessary, as a supplement Add Ravelu Reference Edition.

There is no method that refers to a new value, which means that your code will currently fail to compile it:

  std :: function & lt; Void () & gt; Func ([] () {/ * some clever /}); // do something necessary with func, perhaps debug logging or debug buttons- & gt; On (Event Type :: Click, Function);   

For simplicity, whenever you choose to pass a value, you can follow these guidelines in general:

  • If you need a copy or intends to modify the sent value without the desire to change the actual object: Passed value.
  • If you intend to modify the value you send, and want to make these changes affect the actual object: pass by reference.
  • If you do not want to pass the object, but believe that it is beneficial to avoid copying: pass from context.
  • If you take the criteria from the value, context or const context, and believe that there are valuable customizations which can be achieved by using the knowledge that the input parameter is a temporary one: it also passes from the rvalue context Allows to

No comments:

Post a Comment