News

Promise-Cpp with Boost.Beast -- Richard Thomson

Utah C++ Programmers has released a new video:

Promise-Cpp with Boost.Beast

by Richard Thomson

From the video description:

Over the past few months, we've looked at asynchronous I/O and network programming using Boost.Asio and Boost.Beast. Those libraries connect to your application through the use of callbacks. When orchestrating a sequence of asynchronous operations, it is up to the application to ensure that the callbacks are invoked in the proper sequence.

This "callback hell" problem has long been recognized in the JavaScript world, as all I/O operations in JavaScript (timers or XML HTTP Requests) are asynchronous. In the JavaScript world this lead to promise oriented APIs that allowed for a more linear notation in expressing a sequence of asynchronous operations. This led to the Promises/A+ specification for JavaScript promises.

Promise-cpp is an implementation of the Promises/A+ specification for C++. It can integrate with Boost.Asio and Boost.Beast for asynchronous network programming support for low-level I/O as well as HTTP and WebSocket APIs.

https://www.youtube.com/watch?v=YnTaumB5HVM

On Writing Loops in Continuation-passing Style, Part 4 -- Raymond Chen

RaymondChen_5in-150x150.jpgIn this article, we delve into the equivalent helper functions for C# and JavaScript, which are simpler due to the inherent behavior of references in these languages, eliminating the need for explicit shared pointer conversions. 

On Writing Loops in Continuation-passing Style, Part 4

By Raymond Chen

From the article:

So far, we’ve been look at writing loops in PPL and continuation-passing style, and a lot of the complications came from creating shared_ptrs to manage shared state without copying, and trying to reduce the number of such pointers we had to make. The equivalent helper functions in C# and JavaScript are simpler because in those languages, references act like shared_ptr already; there’s no need to convert them into shared pointers explicitly.

class TaskHelpers
{
    public static Task DoWhileTask(Func<Task<bool>> callable)
    {
        return callable().ContinueWith(t =>
            t.Result ? DoWhileTask(callable)
                     : Task.CompletedTask).Unwrap();
    }
}

The C# Task Parallel Library’s ContinueWith method is the equivalent to the PPL then() method: You give it a Func<Task<T>, Result> which is called with the preceding task. In our case, we are given a Task<bool>: We check the result, and if it is true, then we recurse back and do the whole thing again.

The gotcha is that ContinueWith returns a task whose result type matches the return value of the Func you passed in. In our case, that Func returns a Task, so the return value of ContinueWith is a rather confusing Task<Task>. You need to follow up with the Unwrap() method to unwrap one layer and get a Task back. (More generally, the Unwrap method converts a Task<Task<T>> to a Task<T>.)

Optional Polymorphism by Delegation -- Daniel Lindner

softwareschmiede_logo-1-300x138.pngA code design pattern I’ve used a lot in recent times is the “optional-based polymorphism” that looks like a delegation to another type that might not be available. It might be an implementation of the FCoI-principle (Favour Composition over Inheritance).

Optional Polymorphism by Delegation

By Daniel Lindner

From the article:

Let’s look at an example: An application has several different engines that move stuff around. Some engines are based on limit switches. They move until they are stopped by a physical switch. The application can make these engines move from one predefined position to the next, but not anywhere in between. Another type of engines is based on a relative position. You give the engine the new target position and it positions itself there, without any limit switches or predefined positions.

Traditional approach

A typical implementation using inheritance would be a common supertype “Engine” that provides the functionality both engine types exhibit. From there, we would define two subtypes that extend the functionality in their desired way. One subtype would be the “LimitSwitchEngine”, the other one the “PositionableEngine”.

Our client code that wants to use a particular engine has two possibilities: It only requires the common functionality of an engine and can work with the supertype. Or it needs to perform a downcast after checking the actual type of the engine.

On Writing Loops in PPL and Continuation-passing Style, Part 3 -- Raymond Chen

RaymondChen_5in-150x150.jpgIn our previous discussion, we optimized a task-based while loop by eliminating nested shared pointers, instead requiring all the state to reside inside a caller-provided shared_ptr, making the callable stateless. This approach simplifies the code and reduces redundancy in managing state.

On Writing Loops in PPL and Continuation-passing Style, Part 3

By Raymond Chen

From the article:

Last time, we wrote a task-based while loop using recursion, using a shared_ptr to pass state, and we noted a redundancy in that we created a shared_ptr to a lambda that in turn held a shared_ptr.

We can eliminate the nested shared pointers by requiring that all the state live inside a caller-provided shared_ptr, levaing the callable stateless.

template<typename State>
task<void> do_while_task(
    std::shared_ptr<State> const& state,
    bool (*f)(std::shared_ptr<State> const&)
{
    return f(state).then([state, f](bool loop) {
        return loop ? do_while_task(state, f) :
                      task_from_result();
    });
}

struct lambda_state
{
    lambda_state(Widgets* w) : widgets(w) {}
    Widgets* widgets;
    int i = 0;
};

auto state = std::make_shared<lambda_state>(widgets);

do_while_task(state, [](auto&& state)
{
    if (state->i >= 3) return task_from_result(false);
    return create_widget().then([state](auto widget)
    {
        state->widgets[state->i] = widget;
        state->i++;
        return true;
    }
}).then([] {
    printf("Done!\n");
});

We can get rid of all the state-> prefixes by making the state be invocable.

CopperSpice: Time to Sort Out std::chrono

New video on the CopperSpice YouTube Channel:

Time to Sort Out std::chrono

by Barbara Geller and Ansel Sermersheim

About the video:

We just posted a new video about std::chrono. It provides an overview of the functionality which was added in C++11, C++17, and C++20. Please watch to find out how much of std::chrono your compiler actually supports. We were pretty surprised at what we discovered.

Please take a look and remember to subscribe.

ACCU 2024 Call for Speakers -- ACCU

The ACCU is now putting together its program, and they want you to speak on C++. The ACCU conference has strong C++ tracks, though it is not a C++-only conference. If you have something to share, check out their

Call for Speakers

by ACCU 

About the conference:

The ACCU Conference is the annual conference of the ACCU membership, but is open to any and all who wish to attend. The tagline for the ACCU is "Professionalism in Programming", which captures the whole spectrum of programming languages, tools, techniques and processes involved in advancing our craft. While there remains a core of C and C++ - with many members participating in respective ISO standards bodies - the conference, like the organisation, embraces other language ecosystems and you should expect to see sessions on C#, D, F#, Go, Javascript, Haskell, Java, Kotlin, Lisp, Python, Ruby, Rust, Swift and more. There are always sessions on TDD, BDD, and how to do programming right.

The ACCU Conference is a conference by programmers for programmers about programming.

The Call For Speakers will remain open until midnight (GMT) on 17th November 2023.

WG21 Varna Trip Report -- David Sankel

David Sankel discusses about the developments at the June 2023 ISO C++ standardization meeting in Varna.

WG21 Varna Trip Report

by David Sankel

About the report:

In detail he speakes about std::simd, std::inplace_vector, and other developments.

Beautiful C++: 30 Core Guidelines... Book Review -- Bartlomiej Filipek

beautiful_cpp.jpgThis is a book review of “Beautiful C++,” written by two well-known C++ experts and educators: Kate Gregory and Guy Davidson. The book’s unique style gives us a valuable perspective on effective and safe C++ code.

Beautiful C++: 30 Core Guidelines... Book Review

By Bartlomiej Filipek

From the review:

The book is split into five parts, and each part has six guidelines to help us understand the material more easily.

  • Part one: Bikeshedding is bad - how to reduce the number of lines of your code and simplify it. For example, by using use in-class member initializers or avoiding getters and setters.
  • Part two: Don’t hurt yourself - how to avoid messy code and minimize complexity. For example, by limiting explicit sharing of variables, proper use of ABI and more.
  • Part three: Stop using that - some important bugs and bad C++ code style: singletons, casting away const or unsafe managing the ownership of resources.
  • Part four: Use this new thing properly - efficient use of modern C++ style: enum classes, constexpr, templates.
  • Part five: Write code well by default - good patterns for your code: type safety, immutable data structures avoiding uninitialized variables, and RAII.

In total, it’s around 300 pages + afterword and index.

If we look at a corresponding guideline like I.3: Avoid singletons you’ll see a short paragraph of introduction, some small example and a short discussion to alternatives. On the other hand, in the book, this guideline consists of 9 pages with unique examples, backstories, alternatives and discussions. The section shows things like:

  • Why global objects are bad
  • Singleton Design pattern overview
  • Static initialization order fiasco
  • Hiding singletons and making a namespace rather than a class
  • And even how to use constexpr in some cases (constexpr is also covered in other sections)