Codementor Events

Success and error callbacks with C++ Lambdas

Published Jun 15, 2021
Success and error callbacks with C++ Lambdas

Today we’ll take a quick look at how you can implement success and error callbacks using Modern C++ lambdas.

As I was implementing our in-app purchase client in our app, I had to make some HTTP calls to retrieve various files/data. I decided to wrap the system-dependent iOS/macOS code in a simple HTTP class, with two extra templated parameters that serve as success/failure callbacks.

Here’s a pretty straightforward way to provide two semi-anonymous lambdas to a class.


alt

Now, here’s a straightforward helper function to create a new HTTPRequest:

alt

Now let’s see a real world example:

alt

The class is very straightforward and lacks a couple of things but you get the idea.

Lambda’s are definitely super useful in different scenarions and I have found myself heavily relying on them since Xcode started to support C++11.

Cheers!

Discover and read more posts from Mathieu Garcia
get started