Functional exceptionless error-handling with optional and expected

Simon Brand from Simon Brand

In software things can go wrong. Sometimes we might expect them to go wrong. Sometimes it’s a surprise. In most cases we want to build in some way of handling these misfortunes. Let’s call them disappointments. I’m going to exhibit how to use std::optional and the proposed std::expected to handle disappointments, and show how the types can be extended with concepts from functional programming to make the handling concise and expressive.

One way to express and handle disappointments is exceptions:

void foo() {
try {
do_thing();
}
catch (...) {
//oh no
handle_error();
}
}

There are a myriad of discussions, resources, rants, tirades, debates about the value of exceptions123456, and I will not repeat them here. Suffice to say that there are cases in which exceptions are not the best tool for the job. For the sake of being uncontroversial, I’ll take the example of disappointments which are expected within reasonable use of an API.

The internet loves cats. The hypothetical you and I are involved in the business of producing the cutest images of cats the world has ever seen. We have produced a high-quality C++ library geared towards this sole aim, and we want it to be at the bleeding edge of modern C++.

A common operation in feline cutification programs is to locate cats in a given image. How should we express this in our API? One option is exceptions:

// Throws no_cat_found if a cat is not found.
image_view find_cat (image_view img);

This function takes a view of an image and returns a smaller view which contains the first cat it finds. If it does not find a cat, then it throws an exception. If we’re going to be giving this function a million images, half of which do not contain cats, then that’s a lot of exceptions being thrown. In fact, we’re pretty much using exceptions for control flow at that point, which is A Bad Thing™.

What we really want to express is a function which either returns a cat if it finds one, or it returns nothing. Enter std::optional.

std::optional<image_view> find_cat (image_view img);

std::optional was introduced in C++17 for representing a value which may or may not be present. It is intended to be a vocabulary type – i.e. the canonical choice for expressing some concept in your code. The difference between this signature and the last is powerful; we’ve moved the description of what happens on an error from the documentation into the type system. Now it’s impossible for the user to forget to read the docs, because the compiler is reading them for us, and you can be sure that it’ll shout at you if you use the type incorrectly.

The most common operations on a std::optional are:

std::optional<image_view> full_view = my_view;
std::optional<image_view> empty_view;
std::optional<image_view> another_empty_view = std::nullopt;

full_view.has_value(); //true
empty_view.has_value(); //false

if (full_view) { this_works(); }

my_view = full_view.value();
my_view = *full_view;

my_view = empty_view.value(); //throws bad_optional_access
my_view = *empty_view; //undefined behaviour

Now we’re ready to use our find_cat function along with some other friends from our library to make embarrassingly adorable pictures of cats:

std::optional<image_view> get_cute_cat (image_view img) {
auto cropped = find_cat(img);
if (!cropped) {
return std::nullopt;
}

auto with_tie = add_bow_tie(*cropped);
if (!with_tie) {
return std::nullopt;
}

auto with_sparkles = make_eyes_sparkle(*with_tie);
if (!with_sparkles) {
return std::nullopt;
}

return add_rainbow(make_smaller(*with_sparkles));
}

Well this is… okay. The user is made to explicitly handle what happens in case of an error, so they can’t forget about it, which is good. But there are two issues with this:

  1. There’s no information about why the operations failed.
  2. There’s too much noise; error handling dominates the logic of the code.

I’ll address these two points in turn.

Why did something fail?

std::optional is great for expressing that some operation produced no value, but it gives us no information to help us understand why this occurred; we’re left to use whatever context we have available, or (God forbid) output parameters. What we want is a type which either contains a value, or contains some information about why the value isn’t there. This is called std::expected.

Now don’t go rushing off to cppreference to find out about std::expected; you won’t find it there yet, because it’s currently a standards proposal rather than a part of C++ proper. However, its interface follows std::optional pretty closely, so you already understand most of it. Again, here are the most common operations:

std::expected<image_view,error_code> full_view = my_view;
std::expected<image_view,error_code> empty_view = std::unexpected(that_is_a_dog);

full_view.has_value(); //true
empty_view.has_value(); //false

if (full_view) { this_works(); }

my_view = full_view.value();
my_view = *full_view;

my_view = empty_view.value(); //throws bad_expected_access
my_view = *empty_view; //undefined behaviour

auto code = empty_view.error();
auto oh_no = full_view.error(); //undefined behaviour

With std::expected our code might look like this:

std::expected<image_view, error_code> get_cute_cat (image_view img) {
auto cropped = find_cat(img);p
if (!cropped) {
return no_cat_found;
}

auto with_tie = add_bow_tie(*cropped);
if (!with_tie) {
return cannot_see_neck;
}

auto with_sparkles = make_eyes_sparkle(*with_tie);
if (!with_sparkles) {
return cat_has_eyes_shut;
}

return add_rainbow(make_smaller(*with_sparkles));
}

Now when we call get_cute_cat and don’t get a lovely image back, we have some useful information to report to the user as to why we got into this situation.

Noisy error handling

Unfortunately, with both the std::optional and std::expected versions, there’s still a lot of noise. This is a disappointing solution to handling disappointments. It’s also the limit of what C++17’s std::optional and the most recent proposed std::expected give us.

What we really want is a way to express the operations we want to carry out while pushing the disappointment handling off to the side. As is becoming increasingly trendy in the world of C++, we’ll look to the world of functional programming for help. In this case, the help comes in the form of what I’ll call map and and_then.

If we have some std::optional and we want to carry out some operation on it if and only if there’s a value stored, then we can use map:

widget do_thing (const widget&);

std::optional<widget> result = maybe_get_widget().map(do_thing);
auto result = maybe_get_widget().map(do_thing); //or with auto

This code is roughly equivalent to:

widget do_thing (const widget&);

auto opt_widget = maybe_get_widget();
if (opt_widget) {
widget result = do_thing(*opt_widget);
}

If we want to carry out some operation which could itself fail then we can use and_then:

std::optional<widget> maybe_do_thing (const widget&);

std::optional<widget> result = maybe_get_widget().and_then(maybe_do_thing);
auto result = maybe_get_widget().and_then(maybe_do_thing); //or with auto

This code is roughly equivalent to:

std::optional<widget> maybe_do_thing (const widget&);

auto opt_widget = maybe_get_widget();
if (opt_widget) {
std::optional<widget> result = maybe_do_thing(*opt_widget);
}

and_then and map for expected acts in much the same way an for optional: if there is an expected value then the given function will be called with that value, otherwise the stored unexpected value will be returned. Additionally, we could add a map_error function which allows mapping functions over unexpected values.

The real power of these functions comes when we begin to chain operations together. Let’s look at that original get_cute_cat implementation again:

std::optional<image_view> get_cute_cat (image_view img) {e
auto cropped = find_cat(img);
if (!cropped) {
return std::nullopt;
}

auto with_tie = add_bow_tie(*cropped);
if (!with_tie) {
return std::nullopt;
}

auto with_sparkles = make_eyes_sparkle(*with_tie);
if (!with_sparkles) {
return std::nullopt;
}

return add_rainbow(make_smaller(*with_sparkles));
}

With map and and_then, our code transforms into this:

tl::optional<image_view> get_cute_cat (image_view img) {
return crop_to_cat(img)
.and_then(add_bow_tie)
.and_then(make_eyes_sparkle)
.map(make_smaller)
.map(add_rainbow);
}

With these two functions we’ve successfully pushed the error handling off to the side, allowing us to express a series of operations which may fail without interrupting the flow of logic to test an optional. For more discussion about this code and the equivalent exception-based code, I’d recommend reading Vittorio Romeo’s Why choose sum types over exceptions? article.

A theoretical aside

I didn’t make up map and and_then off the top of my head; other languages have had equivalent features for a long time, and the theoretical concepts are common subjects in Category Theory.

I won’t attempt to explain all the relevant concepts in this post, as others have done it far better than I could. The basic idea is that map comes from the concept of a functor, and and_then comes from monads. These two functions are called fmap and >>= (bind) in Haskell. The best description of these concepts which I have read is Functors, Applicatives’ And Monads In Pictures by Aditya Bhargava. Give it a read if you’d like to learn more about these ideas.

A note on overload sets

One use-case which is annoyingly verbose is passing overloaded functions to map or and_then. For example:

int foo (int);

tl::optional<int> o;
o.map(foo);

The above code works fine. But as soon as we add another overload to foo:

int foo (int);
int foo (double);

tl::optional<int> o;
o.map(foo);

then it fails to compile with a rather unhelpful error message:

test.cpp:7:3: error: no matching member function for call to 'map'
o.map(foo);
~~^~~
/home/simon/projects/optional/optional.hpp:759:52: note: candidate template ignored: couldn't infer template argument 'F'
  template <class F> TL_OPTIONAL_11_CONSTEXPR auto map(F &&f) & {
                                                   ^
/home/simon/projects/optional/optional.hpp:765:52: note: candidate template ignored: couldn't infer template argument 'F'
  template <class F> TL_OPTIONAL_11_CONSTEXPR auto map(F &&f) && {
                                                   ^
/home/simon/projects/optional/optional.hpp:771:37: note: candidate template ignored: couldn't infer template argument 'F'
  template <class F> constexpr auto map(F &&f) const & {
                                    ^
/home/simon/projects/optional/optional.hpp:777:37: note: candidate template ignored: couldn't infer template argument 'F'
  template <class F> constexpr auto map(F &&f) const && {
                                    ^
1 error generated.

One solution for this is to use a generic lambda:

tl::optional<int> o;
o.map([](auto x){return foo(x);});

Another is a LIFT macro:

#define FWD(...) std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)
#define LIFT(f) \
[](auto&&... xs) noexcept(noexcept(f(FWD(xs)...))) -> decltype(f(FWD(xs)...)) \
{ return f(FWD(xs)...); }

tl::optional<int> o;
o.map(LIFT(foo));

Personally I hope to see overload set lifting get into the standard so that we don’t need to bother with the above solutions.

Current status

Maybe I’ve persuaded you that these extensions to std::optional and std::expected are useful and you would like to use them in your code. Fortunately I have written implementations of both with the extensions shown in this post, among others. tl::optional and tl::expected are on GitHub as single-header libraries under the CC0 license, so they should be easy to integrate with projects new and old.

As far as the standard goes, there are a few avenues being entertained for adding this functionality. I have a proposal to extend std::optional with new member functions. Vicente Escribá has a proposal for a generalised monadic interface for C++. Niall Douglas’ operator try() paper suggests an analogue to Rust’s try! macro for removing some of the boilerplate associated with this style of programming. It turns out that you can use coroutines for doing this stuff, although my gut feeling puts this more to the “abuse” end of the spectrum. I’d also be interested in evaluating how Ranges could be leveraged for these goals.

Ultimately I don’t care how we achieve this as a community so long as we have some standardised solution available. As C++ programmers we’re constantly finding new ways to leverage the power of the language to make expressive libraries, thus improving the quality of the code we write day to day. Let’s apply this to std::optional and std::expected. They deserve it.


New Tech Startups born in 54 hour Sync The City event

Paul Grenyer from Paul Grenyer

From the moment I walked into the refectory at the Cathedral, ahead of the Saturday night pitches, I felt there was something special going to happen. It wasn’t until the pitches actually began an hour or so later, that I realised exactly what it was.

I’m ashamed to say I’ve never been to Sync The City, despite it being in its fourth year. The idea behind the event it to build a tech based startup in just 54 hours and then pitch for funding at the end. It was these final pitches I had come to see.

Twelve startups waited anxiously for Fiona Lettice, the Pro-Vice-Chancellor of the UEA, SyncNorwich and Sync The City organiser, to make her introduction to this year's event. She described Sync The City as The Apprentice crossed with Dragon’s Den, with all the tension and hard work compressed into a little over two days. With this, and the prize of £3,000 in funding on their minds, the twelve groups began their pitches.

When I’d been in the refectory earlier there was clearly some concern about these pitches, but every single one was excellent. I was expecting lots of hesitation in the delivery, having been put together under the pressure of the time limit, but there was hardly any. The styles, methods, number of presenters, etc. for each pitch varied greatly, which helped keep my interest to the end.

By only the second pitch I knew what it was that felt special when I had arrived. It was the sense of comradery shared by everyone who was taking part - a real feeling that they were all in it together, regardless of who won at the end of it all.

There was a clear winner for me - a team called Footprint whose product helped individuals identify all of their data on the internet.


The People’s Prize, as voted for by the audience, went to Unwind, a chatbot intended to help with mental illness.



The official judges, Ian Watson (CEO Start-rite shoes), Chris Sargisson (CEO Norfolk Chamber), Kirsty Jarvis (CEO Luminus PR and Jazz Singer), Juliana Mayer (CEO SupaPass) and Wayne Taylor (CTO Thyngs) chose Lone Safe, a team who developed a system for keeping lone workers safe, as the overall winner.



The runners up were a team called ViaCab who were developing an app for hailing Black Cabs.



The explosion of excitement from the winning team and the audience alike was incredible! After Lone Safe were led off to sign the paperwork for their prize money, and Sean Clark brought the event to a close, they could be heard still celebrating in a side room, excited to be able to make their startup a reality.

I don’t have hope

Samathy from Stories by Samathy on Medium

I don’t have hope about the state of society regarding support of trans people.

On Trans Day of Remembrance 2017 I organised and spoke at Coventry Pride’s event.
I delivered the following words to the attendees. Since I spent so much time crying over writing them, I’ll share them with you too.

Hope is defined in the Cambridge English Dictionary as: To want something to happen or to be true, and usually have a good reason to think that it might.

I am without hope.

As a trans person, although there is so much I want to happen or be true, I can’t see a good reason to think that these things will come to pass.

I dream of fast access to the health care I need.
Access to supportive and knowledgeable professionals whose job it is to know everything there is to know about existing treatments and who might need them. Professionals who listen to and provide for the needs of those who come into their care.
Professionals who are there to help, no matter what your label.
I dream of access to counsellors with whom I can freely discuss my problems and the mess of feelings without the weight of a cost, or time limit above me.

I shouldn’t have to resort to private care.

What we have, is a system of gatekeeping and long waiting lists where the people in need of care often know better what they need and what is available than the professionals with the authority to prescribe them that care.
Despite the pain trans people suffer every day, we have a system which is there to stop us getting care, rather than support us.

I want this system to improve, with a struggling NHS, I don’t see it happening fast enough to help many of those on the waiting lists in time.

I wish we could go a few months without an awful media story or TV show that insults and degrades trans people.

I wish I could wake up and see a trans person presenting the news, or an kids show with boys in skirts and girls in a tie.
I wish I could see bbc news headlines of surprise that someone would attack a trans person, in this day and age, rather than it being the headlines themselves attacking trans people.

But being trans is still controversial, theres still money in writing about and presenting us to those in society who hate us, think we’re weird and a waste of space.

I wish this would get better, but It’ll be a while before the bigots die out. Still long enough to make a few more 1000s of pounds on front-page articles, disgusting language and direct verbal attacks on morning TV.

I long to see gender studies taught in schools, for being trans to be a non-issue for everyone, for gender neutral facilities and language to be expected rather than a pleasant, rare, surprise.

I long to see children exploring their surroundings without the bounding of gender, freely learning who they are without feeling wrong, outlawed or upset if they don’t feel quite right about the gender they’re perceived to be.

I long to read a document that says Mr, Mrs, Mx and offers free text for your gender or skips it entirely.

This is closer to reality, but still nowhere near. Theres lots of places I don’t feel safe, lots of companies who just don’t understand, lots of children who still feel trapped and alone.

I don’t have hope.

But I do believe.

I believe in the power of this community to keep fighting and changing.
That we will support and protect our own.
That we will remember the friends no longer with us.
That we will remember our past and protest for a better future.
That we will educate and inspire.
That we will punch the nazis and remove the transphobes from power.
That we will complain to companies when their title and gender options are from the dark ages.
That we will write counter article after counter article until the media understand.

I believe that we will make a difference.

Event: How Norfolk Chamber of Commerce can help digital business!

Paul Grenyer from Paul Grenyer


How Norfolk Chamber of Commerce can help digital business

When: Tuesday 5th December, 7.30am to 8.30am.


How much: £13.95


7.30 am Breakfast

7.50 am How Norfolk Chamber of Commerce can help digital business

8.30 am Finish

Successful Norfolk entrepreneur Chris Sargisson was appointed as Chief Executive of Norfolk Chamber of Commerce in June 2017. Chris was educated in Norwich and lives in the city with his wife and two children. He worked in the 1990s shaping Norwich Union Direct before leaving to set up and launch its4me plc, one of the UK’s most successful online car insurance brokers and major Norwich employer. Chris also created House Revolution, one of the UK’s first online estate agencies, alongside running his own business consultancy practice which has helped organisations of all sizes across the UK.

At the nor(Dev) breakfast, Chris will explain how Norfolk Chamber can help you to raise the profile of your digital business, highlight you as an expert in your sector and increase awareness of your brand. Chris will demonstrate how Norfolk Chamber can ensure your business content, press releases and promotions reach the maximum number of potential readers.

Free parking is available at the Maids Head, but make sure you give your car registration number to reception before you leave so as not to be charged.

Lucky Sevens – baron m.

baron m. from thus spake a.k.

Greetings Sir R-----! This evening's chill wind might be forgiven some of its injurious assault upon me by delivering me some good company as I warm my bones. Come, shed your coat and join me in a glass of this rather delightful mulled cyder!

Might you be interested in a little sport whilst we recover?

Excellent!

This foul zephyr puts me in mind of the infantile conflict between King Oberon and Queen Titania that was in full force during my first visit to the faerie kingdom. I had arrived there quite by accident but fortunately my reputation was sufficient to earn me an invitation to dine at the King's table. That the fare was sumptuous beyond the dreams of mortal man goes without saying, but the conflict between the King and his consort cast something of a shadow upon the evening.

Emacs on the Linux Subsystem for Windows

Timo Geusch from The Lone C++ Coder&#039;s Blog

I’ve had the Linux Subsystem for Windows enabled for quite a while during the time it was in Beta. With the release of the Fall Creators Update, I ended up redoing my setup from scratch. As usual I grabbed Emacs and a bunch of other packages and was initially disappointed that I was looking at […]

The post Emacs on the Linux Subsystem for Windows appeared first on The Lone C++ Coder's Blog.

Meeting C++17 Trip Report

Simon Brand from Simon Brand

This year was my first time at Meeting C++. It was also the first time I gave a full-length talk at a conference. But most of all it was a wonderful experience filled with smart, friendly people and excellent talks. This is my report on the experience. I hope it gives you an idea of some talks to watch when they’re up on YouTube, and maybe convince you to go along and submit talks next year! I’ll be filling out links to the talks as they go online.

The Venue

The conference was held at the Andel’s Hotel in Berlin, which is a very large venue on the East side of town, about 15 minutes tram ride from Alexanderplatz. All the conference areas were very spacious and there were always places to escape to when you need a break from the noise, or places to sit down on armchairs when you need a break from sitting down on conference chairs.

The People

Some people say they go to conferences for the talks, and for the opportunity to interact with the speakers in the Q&As afterwards. The talks are great, but I went for the people. I had a wonderful time meeting those whom I knew from Twitter or the CppLang Slack, but had never encountered in real life; catching up with those who I’ve met at other events; and talking to those I’d never had interacted with before. There were around 600 people at the conference, primarily from Europe, but many from further-afield. I didn’t have any negative encounters with anyone at the conference, and Jens was very intentional about publicising the Code of Conduct and having a diverse team to enforce it, so it was a very positive atmosphere.

Day 1

Keynote: Sean Parent – Better Code: Human interface

After a short introduction from Jens, the conference kicked off with a keynote from Sean Parent. Although he didn’t say it in these words, the conclusion I took out of it was that all technology requires some thought about user experience (UX if we’re being trendy). Many of us will think of UX as something centred around user interfaces, but it’s more than that. If you work on compilers (like I do), then your UX work involves consistent compiler flags, friendly error messages and useful tooling. If you work on libraries, then your API is your experience. Do your functions do the most obvious thing? Are they well-documented? Do they come together to create terse, correct, expressive, efficient code? Sean’s plea was for us to consider all of these things, and to embed them into how we think about coding. Of course, it being a talk about good code from Sean Parent, it had some great content about composing standard algorithms. I would definitely recommend checking out the talk if what I’ve just written sounds thought-provoking to you.

Peter Goldsborough – Deep Learning with C++

Peter gave a very well-structured talk, which went down the stack of technology involved in deep learning – from high-level libraries to hardware – showing how it all works in theory. He then went back up the stack showing the practical side, including a few impressive live demos. It covers a lot of content, giving a pretty comprehensive introduction. It does move at a very quick pace though, so you probably don’t want to watch this one on 1.5x on YouTube!

Jonathan Boccara – Strong types for strong interfaces

This talk was quite a struggle against technical difficulties; starting 15 minutes late after laptop/projector troubles, then having Keynote crash as soon as the introduction was over. Fortunately, Jonathan handled it incredibly well, seeming completely unfazed as he gave an excellent presentation and even finished on time.

The talk itself was about using strong types (a.k.a. opaque typedefs) to strengthen your code’s resilience to programmer errors and increase its readability. This was a distillation of some of the concepts which Jonathan has written about in a series on his blog. He had obviously spent a lot of time rehearsing this talk and put a lot of thought into the visual design of the slides, which I really appreciated.

Simon Brand (me!) – How C++ Debuggers Work

This was my first full length talk at a conference, so I was pretty nervous about it, but I think it went really well: there were 150-200 people there, I got some good questions, and a bunch of people came to discuss the talk with me in the subsequent days. I screwed up a few things – like referring to the audience as “guys” near the start and finishing a bit earlier than I would have liked – but all in all it was a great experience.

My talk was an overview of almost all of the commonly-used parts of systems-level debuggers. I covered breakpoints, stepping, debug information, object files, operating system interaction, expression evaluation, stack unwinding and a whole lot more. It was a lot of content, but I think I managed to get a good presentation on it. I’d greatly appreciate any feedback of how the talk could be improved in case I end up giving it at some other conference in the future!

Joel Falcou – The Three Little Dots and the Big Bad Lambdas

I’m a huge metaprogramming nerd, so this talk on using lambdas as a kind of code injection was very interesting for me. Joel started the talk with an introduction to how OCaml allows code injection, and then went on to show how you could emulate this feature in C++ using templates, lambdas and inlining in C++. It turned out that he was going to mostly talk about the indices trick for unpacking tuple-like things, fold expressions (including how to emulate them in C++11/14), and template-driven loop unrolling – all of which are techniques I’m familiar with. However, I hadn’t thought about these tools in the context of compile-time code injection, and Joel presented them very well, so it was still a very enjoyable talk. I particularly enjoyed hearing that he uses these in production in his company in order to fine-tune performance. He showed a number of benchmarks of the linear algebra library he has worked on against another popular implementation which hand-tunes the code for different architectures, and his performance was very competitive. A great talk for demonstrating how templates can be used to optimise your code!

Diego Rodriguez-Losada – Conan C++ Quiz

This was one of the highlights of the whole conference. The questions were challenging, thought-provoking, and hilarious, and Diego was a fantastic host. He delivered all the content with charisma and wit, and was obviously enjoying himself: maybe my favourite part of the quiz was the huge grin he wore as everyone groaned in incredulity when the questions were revealed. I don’t know if the questions will go online at some point, but I’d definitely recommend giving them a shot if you get the chance.

Day 2

Keynote: Kate Gregory – It’s complicated!

Kate gave a really excellent talk which examined the complexities of writing good code, and those of C++. The slide which I saw the most people get their phones out for said “Is it important to your ego that you’re really good at a complicated language?”, which I think really hit home for many of us. C++ is like an incredibly intricate puzzle, and when you solve a piece of it, you feel good about it and want to share your success with others. However, sometimes, we can make that success, that understanding, part of our identity. Neither Kate or I are saying that we shouldn’t be proud of our domination over the obscure parts of the language, but a bit of introspection about how we reflect this understanding and share it with others will go a long way.

Another very valuable part of her talk was her discussion on the importance of good names, and how being able to describe some idiom or pattern helps us to talk about it and instruct others. Of course, this is what design patterns were originally all about, but Kate frames it in a way which helps build an intuition around how this common language works to make us better programmers. A few days after the conference, this is the talk which has been going around my head the most, so if you watch one talk from this year’s conference, you could do a lot worse than this one.

Felix Petriconi – There Is A New Future

Felix presented the std::future-a-like library which he and Sean Parent have been working on. It was a very convincing talk, showing the inadequacies of std::future, and how their implementation fixes these problems. In particular, Felix discussed continuations, cancellations, splits and forks, and demonstrated their utility. You can find the library here.

Lukas Bergdoll – Is std::function really the best we can do?

If you’ve read a lot of code written by others, I’m sure you’ll have seen people misusing std::function. This talk showed why so many uses are wrong, including live benchmarks, and gave a number of alternatives which can be used in different situations. I particularly liked a slide which listed the conditions for std::function to be a good choice, which were:

  • It has to be stored inside a container
  • You really can’t know the layout at compile time
  • All your callable types are move and copyable
  • You can constrain the user to exactly one signature

#include meeting

Guy Davidson lead an open discussion about #include, which is a diversity group for C++ programmers started by Guy and Kate Gregory (I’ve also been helping out a bit). It was a very positive discussion in which we shared stories, tried to grapple with some of the finer points of diversity and inclusion in the tech space, and came up with some aims to consider moving forward. Some of the key outcomes were:

  • We should be doing more outreach into schools and trying to encourage those in groups who tend to be discouraged from joining the tech industry.
  • Some people would greatly value a resource for finding companies which really value diversity rather than just listing it as important on their website.
  • Those of use who care about these issues can sometimes turn people away from the cause by not being sensitive to cultural, psychological or sociological issues; perhaps we need education on how to educate.

I thought this was a great session and look forward to helping develop this initiative and seeing where we can go with it. I’d encourage anyone who is interested to get on to the #include channel on the CppLang Slack, or to send pull requests to the information repository.

Juan Bolívar – The most valuable values

Juan gave a very energetic, engaging talk about value semantics and his Redux-/Elm-like C++ library, lager. He showed how these techniques can be used for writing clear, correct code without shared mutable state. I particularly like the time-travelling debugger which he presented, which allows you to step around the changes to your data model. I don’t want to spoil anything, but there’s a nice surprise in the talk which gets very meta.

Day 3

Lightning talks

I spent most of day three watching lightning talks. There were too many to discuss individually, so I’ll just mention my favourites.

Arvid Gerstmann – A very quick view into a compiler

Arvid gave a really clear, concise description of the different stages of compilation. Recommended if you want a byte-sized introduction to compilers.

Réka Nikolett Kovács – std::launder

It’s become a bit of a meme on the CppLang Slack that we don’t talk about std::launder, as it’s only needed if you’re writing standard-library-grade generic libraries. Still, I was impressed by this talk, which explains the problem well and shows how std::launder (mostly) solves it. I would have liked more of a disclaimer about who the feature is for, and that there are still unsolved problems, but it was still a good talk.

Andreas Weis – Type Punning Done Right

Strict aliasing violations are a common source of bugs if you’re writing low level code and aren’t aware of the rules. Andreas gave a good description of the problem, and showed how memcpy is the preferred way to solve it. I do wish he’d included an example of std::bit_cast, which was just voted in to C++20, but it’s a good lightning talk to send to your colleagues the next time they go type punning.

Miro Knejp – Is This Available?

Miro presented a method of avoiding awful #ifdef blocks by providing a template-based interface to everything you would otherwise preprocess. This is somewhat similar to what I talked about in my if constexpr blog post, and I do something similar in production for abstracting the differences in hardware features in a clean, composable manner. As such, it’s great to have a lightning talk to send to people when I want to explain the concept, and I’d recommend watching it if the description piques your interest. Now we just need a good name for it. Maybe the Template Abstracted Preprocessor (TAP) idiom? Send your thoughts to me and Miro!

Simon Brand (me!) – std::optional and the M word

Someone who was scheduled to do a lightning talk didn’t make the session, so I ended up giving an improvised talk about std::optional and monads. I didn’t have any slides, so described std::optional as a glass which could either be empty, or have a value (in this case represented by a pen). I got someone from the audience to act as a function which would give me a doily when I gave it a pen, and acted out functors and monads using that. It turned out very well, even if I forgot how to write Haskell’s bind operator (>>=) halfway through the talk!

Overall

I really enjoyed the selection of lightning talks. There was a very diverse range of topics, and everything flowed very smoothly without any technical problems. It would have been great if there were more speakers, since some people gave two or even three talks, but that means that more people need to submit! If you’re worried about talking, a lightning talk is a great way to practice; if things go terribly wrong, then the worse that can happen is that they move on to the next speaker. It would have also been more fun if it was on the main track, or if there wasn’t anything scheduled against them.

Secret Lightning Talks

Before the final keynote there was another selection of lightning talks given on the keynote stage. Again, I’ll just discuss my favourites.

Guy Davidson – Diversity and Inclusion

Guy gave a heartfelt talk about diversity in the C++ community, giving reasons why we should care, and what we can do to try and encourage involvement for those in under-represented groups in our communities. This is a topic which is also very important to me, so it was great to see it being given an important place in the conference.

Kate Gregory – Five things I learned when I should have been dying

An even more personal talk was given by Kate about important things she learned when she was given her cancer diagnosis. It was a very inspiring call to not care about the barriers which may perceive to be in the way of achieving something – like, say, going to talk at a conference – and instead just trying your best and “doing the work”. Her points really resonated with me; I, like many of us, have suffered from a lot of impostor syndrome in my short time in the industry, and talks like this help me to battle through it.

Phil Nash – A Composable Command Line Parser

Phil’s talk was on Clara, which is a simple, composable command line parser for C++. It was split off from his Catch test framework into its own library, and he’s been maintaining it independently of its parent. The talk gave a strong introduction to the library and why you might want to use it instead of one of the other hundreds of command line parsers which are out there. I’m a big fan of the design of Clara, so this was a pleasure to watch.

Keynote: Wouter van Ooijen – What can C++ offer embedded, what can embedded offer C++?

To close out the conference, Wouter gave a talk about the interaction between the worlds of C++ and embedded programming. The two have been getting more friendly in recent years thanks to libraries like Kvasir and talks by people like Dan Saks and Odin Holmes. Wouter started off talking about his work on space rockets, then motivated using C++ templates for embedded programming, showed us examples of how to do it, then finished off talking about what the C++ community should learn from embedded programming. If I’m honest, I didn’t enjoy this keynote as much as the others, as I already had an understanding of the techniques he showed, and I was unconvinced by the motivating examples, which seemed like they hadn’t been optimised properly (I had to leave early to catch a plane, so please someone tell me if he ended up clarifying them!). If you’re new to using C++ for embedded programming, this may be a good introduction.

Closing

That’s it for my report. I want to thank Jens for organising such a great conference, as well as his staff and volunteers for making sure everything ran smoothly. Also thanks to the other speakers for being so welcoming to new blood, and all the other attendees for their discussions and questions. I would whole-heartedly recommend attending the conference and submitting talks, especially if you haven’t done so before. Last but not least, a big thanks to my employer, Codeplay for sending me (we’re hiring, you get to work on compilers and brand new hardware and go to conferences, it’s pretty great).

Lisa Vincent Reconnects with her Comfort Zone at nor(DEV):biz.

Paul Grenyer from Paul Grenyer

My comfort zone had left the building.

Heading out on a cold, dark, Monday evening to yet another Norwich networking event is not everyone’s cup of tea. It’s certainly not mine, and definitely not with the cream of the Norfolk tech sector midway through my first attack of a winter cold in I don’t know how long.

We all do things we think might help us to build relationships in business and gain favours with those people around us that might help to push us in the right direction. Accepting an invitation to the November nor(DEV):biz dinner at The Library Restaurant in Norwich was one of those such occasions.

I had worked opposite The Library for about 3 years and not actually made it into the building. Seeing as I have been known to travel many miles through the most challenging of conditions for some decent eats and beautiful architecture, I wrapped myself up and loaded with tissues, I braved the elements resolutely deciding to be back home and in bed by 9:30pm. I could get through this. I would dine and dash.

When I arrived just after 7pm, there were about 20 people gathered in the bar, discussing all manner of tech related topics I knew nothing about. A quick scan revealed that I didn’t know anyone in the room either. I hadn’t just stepped out of my comfort zone. My comfort zone had left the building, the locks had been changed and the eviction notice was nailed firmly to the front door. As my heart sank further into the 120-year old oak floor, one of the other attendees warmly introduced themselves. With that, so did another and third asked if I would like a drink. Result!

We moved upstairs to a private dining room for the main event where I got chatting to a number of people from various sectors, not just tech. We discussed work, families and life, as well as the issues people were facing in business. Which, it turns out, is the same whatever sector you’re in.

The energy in the room was very different to other ‘networking’ events I’ve been to. It felt more human and more open, more confident even. This was a group of some of the brightest minds in Norwich. Intelligent and engaging human beings who are passionate about what they do, enjoying dinner together in lovely surroundings. There was no agenda, no selling, just an unpretentious coming together of intelligent thoughts, ideas and the potential for collaboration with a genuine desire to help each other.

Between courses we listened to a personal account from Laura Flood, Lecturer in IT from City College Norwich, about her own journey into tech and how businesses can help and support new talent into the sector here in Norfolk. If Norfolk is going to be competitive, we need to build the right skills base and create the right jobs for our young people that also benefit the businesses that employ them.

Rather than being irritating, the lengthy delay before the dessert arrived at 10pm, provided a welcome opportunity to talk to even more people in the room. These included software engineers, branding specialists, digital agencies, senior business banking staff and even an accountant.

It seems that in the past, fear may have held me back from exploring the vibrant tech scene we have here in Norwich. If my experience of the nor(DEV)biz: dinner is anything to go by those fears are wholly unfounded. This is an area of business, with a culture, energy and group of individuals I would love to work with more.

I really enjoyed my evening. The food was great, the company fantastic and The Library Restaurant is a stunning location. I’m pleased to report that by the time I left, not only was I firmly reunited with my comfort zone, but we’re planning on attending the December nor(DEV)biz: dinner together.

Words: Lisa Vincent
Norfolk Developers: norfolkdevelopers.com