Category Archives: Programming

C++ London Meetup: Distributed C++

This is the first time that the Stockholm C++ and the London C++ group have combined to produce a series of lightning talks, half given from Sweden and half from England.

Bjorn Fahller: A variant of recursive descent parser
Raised issues with generators and lexers when trying to do this, particularly for debugging. What about std::variant? Has knowledge of the type that it’s holding, and there’s std::visit that can overload function call operators for each type.

// visitor class is defined elsewhere, too far from its declaration!
visitor visitor_obj; 
int i = std::visit(visitor_obj, variant_var );

// Alternative - Bjarne's overload approach with lambdas  
auto t = lexer.next_token();
std::visit(
      overload{
    [=](ident var){ return lookup( var.value); },
    [=](number n){ return n.value;}
  }
  , t );

The template overload makes clever use of deriving from a lambda via templates and C++17 features. The details are here.

Bjarne also referenced: Matt Kline’s post on std::visit is everything wrong with modern c++.

Mikael Rosbacke – Yet another state machine tool
How to make it easy to write state machines? Hierarchy, entry/exit action, queuing, no heap allocations, no code generation.

Mikael’s framework provides a finite state machine base class from which you derive and post events as they arrive. Each state derives from a framework state base class, and provides an event method to transition into other states.

See https://www.github.com/rosbacke/mcu-tools.

Simon Pettersson – The Art of manufacturing types
Compile time lookup-table – with a very convincing demo in compiler explorer, where marking the lookup result as constexpr changed the compiled code to simply a constant.

See https://github.com/simonvpe/cmap

Paul Dreik – what is this std::forward thing?
A beginner’s guide to forwarding references – suppose you want to write a wrapper function that does some action then calls an underlying function. You would need to use std::forward like this, otherwise the wrong overload of function f would be called:

struct S{};

void f(S& s){ puts("f(S&)"); }
void f(S&& s){ puts("f(S&&)"); }

template<typename T>
void wrap(T&& t){
  f(std::forward<T>(t));
}

int main(){
  S s;

  wrap( s );
  wrap( S() );
}

Dominic Jones – Reflecting on names – Facilitating expression tree transforms
Would like to transform expressions differently according to the variable inputs:

transform(a + a) -> 2 * a
transform(a + b) -> a * b

Thoughts are to introduce varid, a keyword based on the position of the declaration of the variables. Evaluated at compile time, a bit like address-of, possibly the hash of the file name, row and column of the referenced variable. The use is for faster automatic differentiation.

Phil Nash – a Composable Command Line Parser
When writing Catch 1.0, Phil wrote Clara 0.x – a command line parser library (but it never reached maturity). As part of Catch 2.0, he has written and completed Clara 1.0! The latest version of the library introduces class Opt which declares command line options, which are then combined with the pipe operator.

auto a = 
      Opt( width, "width" )
        ["-w"]["--width"]
        ("How wide should it be?")
    + Opt( name, "name" )
        ["-n"]["--name"]
        ("By what name should I be known");

See github.com/philsquared.

C++ London University
Tristan is a volunteer at this initiative to support interested parties in learning C++. Hosted by Mirriad, it comprises a mixture of lectures, exercises and covers the basics. 4 meetings so far, looking for tutors and more students! Tristan Brindle – tcbrindle@gmail.com, http://www.cpplondonuni.com, gitHub.com/cpplondonuni

Ian Sheret – Automatic Differentiation in C++
For mathematical functions in various domains. z = f(x,y) e.g. hypotenuse as root of sum of squares in a triangle. But what about values of z near x and y, if we change by some epsilon? Can use Ceres Jets to keep track of the differentiated values. Templatise the function so that you can pass in the Jet variables (instead of simply doubles). Then the return value automatically returns the derivatives as well as the function value!

Andrew Gresyk – Effective Screening Interviews
Consider cultural fit and technical fit – but if they do a separate cultural interview, 80% of people pass that anyway. Need to test communication and ability to write real code – asking knowledge questions only is not sufficient. Replace questions with practical exercises.

Jamie Taylor – Beyond SSO: The Merits of Fixed-Length Strings
std::string – easier and safer to work with than a c string. Handles memory allocation. Uses short string optimisation – short strings go on the stack, so no dynamic allocation.

But – length of SSO buffer is implementation defined. If string is too long, will dynamically allocate. Also, the fixed buffer inside the std::string will frequently be much larger than a very small string you wish to create (typically 32-bytes).

// fl::string is an alternative where the size of the buffer
// is customisable in the template parameters
template<size_t length>
class fl::string
{
  // Implementation elided!
  char m_data[length];
};

Don’t want to pay full cost of e.g. 32 byte std::string if your string will only be 3 characters. This allows you to specify the maximum length in the template. Get average 6x and 13x speed-ups for 8 and 32 character strings for both creation and access of string keys in maps. Can be more friendly for your cache and great for low-latency.

Vittorio Romeo – you must type it out 3 times
Vittorio wants to write a generic log and call method with a noexcept handler – but has to type the same forwarding signature three times! Solution could be the “=>” operator that’s been proposed.

Leave a comment

Filed under C++, Meetup, Programming

Video: Meta – Toward Generative C++, Herb Sutter

Herb Sutter shared this video of his Qt 2017 talk on his personal metaclasses project.  

 

I first heard about this development at ACCU 2017. The benefits of standardising best practices for definitions of interfaces/value types etc are huge and would let the developer concentrate more on the business problem they are solving, rather than the technicalities of the language. 

  

Leave a comment

Filed under C++, Programming, Uncategorized, Video

C++ London Meetup: FFIG and Why Iterators got it Wrong


This month’s C++ London meetup features two talks – the first on C++/Python integration and the second on C++ iterators.

Foreign Function Interface Generator (FFIG) – Jonathan Coe
Jonathan presented his hobby project, FFIG, largely written on the train during his commute (!).

I want to be able to write C++ code and call it from Python without doing any extra work

He explained that existing solutions (Boost::python and SWIG) generate interfaces that bind you to a specific binary Python implementation. Whilst a work in progress, FFIG’s generated libraries are Python library independent (meaning you can compile once and call from multiple Python libraries).

FFIG generates a C-API on top of your C++ code, which eliminates any classes/structs, but provides a library readily callable from Python. It also generates a Python (or Ruby) library that layers the objects over the C-API, to restore the original interface. A key lesson learned during development was to hide any ownership concerns from the Python layer.

Why Iterators Got It Wrong РArno Sch̦dl
Arno has developed a range-like library within his firm (Think-Cell), which addresses some features of iterators perceived as ugly:

// Iterators returned by begin() and end() are asymmetrical
auto it = collection.begin(); // start of a non-empty collection
std::cout << *it; // ok - prints the first element of the collection
auto it2 = collection.end(); // end of a non-empty collection
std::cout << *it2;// error - undefined behaviour, end() returns 1 past the last element!

// Algorithms may return a valid element or a sentinel "border" indicator
std::vector<int> v1{0, 1, 2, 3, 4}, v2{};
auto result1 = std::find(std::begin(v1), std::end(v1), 2);
std::cout << *result1; // ok
auto result2 = std::find(std::begin(v2), std::end(v2), 2);
std::cout << *result2; // error - de-referencing end again

The summary was that his library distinguished between elements and borders instead of using iterators. Once rolled out through the codebase, this made the code clearer and avoided any chance of undefined behaviour. However, I think the availability of Eric Niebler’s Range library (or simple higher-order functions) make the STL so easy to use that these concerns shouldn’t put off new developers.

Leave a comment

Filed under C++, Meetup

ACCU Meetup: Making Templates Easier, Roger Orr

Roger Orr gave this month’s ACCU presentation on Making Templates Easier in C++. He showed two techniques that people commonly use to tailor template implementations for specific types: Tag Dispatch and SFINAE (via enable_if).

With Tag Dispatch, you can switch to different implementations of a template function using traits classes based on one of the input parameter types (e.g. use std::iterator_traits to target a faster implementation for random access iterators). The downside is that you often have to duplicate code across the different implementations.

With SFINAE, you can use typedefs within a parameter type to disable particular overloads. E.g. STL containers have a ::value_type typedef, so you can use that to differentiate between collections and scalar inputs. The downside is that you sometimes have to add additional, defaulted template parameters to allow the compiler to distinguish between otherwise identical template definitions.

Roger then introduced constexpr if from C++17 and concepts from C++20.

The advantages of constexpr if are that it can be used both inside and outside templates and specialisations can be defined inline. Any code that would not compile can be put inside a constexpr if and will be discarded. This seems more straightforward than the recursive template solutions Roger showed earlier in the talk.

Concepts are intended to help define the requirements of a template in a way visible to the compiler as well as the developer. Reusing concept definitions should leave to a domain-specific language that helps within a project. Better still, use of a template parameter type that doesn’t satisfy concept requirements will generate a more helpful error message than if SFINAE were used to achieve the constraints.

The finale was an overview of the new SpaceShip operator, !

The video is now available on the SkillsMatter website.

Leave a comment

Filed under C++, Meetup, Programming

How to draw a triangle in Apple Watch

I’ve previously covered how to draw circles and rectangles into an image when writing an Apple Watch app. I had an idea for another watch face that needed triangles – these need a different approach using Watch Kit. Basically, you have to draw a path around the perimeter of the triangle (or any other shape), then fill in the shape. Here’s a function to draw a triangle that points to the left:

    internal func drawTriangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, size : CGFloat, colour : CGColor )
    {
        context?.beginPath()
        context?.move(to: CGPoint(x: centreX - size/2.0, y: centreY))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY - size/2.0))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY + size/2.0))
        context?.closePath()
        
        context?.setFillColor(colour)
        context?.fillPath()
    }

And this is the code for drawing a rectangle:

    internal func drawRectangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, width : CGFloat, height : CGFloat, colour : CGColor )
    {
        let origin = CGPoint( x: centreX - width/2.0, y : centreY - height/2.0 )
        let rect = CGRect( origin : origin, size : CGSize(width: width, height: height) )
        
        context?.setFillColor(colour)
        context?.fill(rect)
    }

Once you can do those primitive triangle/rectangle operations, you can put them together to render any digit you like. So I used them to draw a ‘timeometer’ in this speedo watch face:

The dial is rendered as a series of ticks – at the moment, it shows minutes and hours. I have to admit I still tend to read the time from the digits at the bottom, so I may change the dial to show seconds and minutes instead.

Leave a comment

Filed under Programming, Swift

How to extend F# discriminated unions for use from C#

Some time ago, I wrote about calling C# byref methods from F#. This time, I wanted to do things in reverse – the motivation being to provide a neat way of working with F# discriminated unions from C#.

Now, some support comes for free when you define a discriminated union in F#. For example, given this union type:

type Vehicle
| Car of int // number of doors
| Lorry of double // weight in tonnes

then from C#, you could query the union case in turn like this:

if (vehicle.IsCar)
{
    var doors = ((Vehicle.Car)vehicle).Item;
    driveCar( doors );
}
else if (vehicle.IsLorry)
{
    var weight = ((Vehicle.Lorry)vehicle).Item;
    driveLorry( weight );
}

However, although the provided “Is” methods are neat, the cast and the requirement to call “.Item” are rather ugly. What you really want is the ability to get the value of the union case without casting. That’s achievable if you add these methods to the original union definition by hand:

using System.Runtime.InteropServices // for [<Out>]
type Vehicle
| Car of int // number of doors
| Lorry of double // weight in tonnes
with
    member this.TryGetCar( [<Out>] result : int byref ) =
        match this with
        | Car doors ->
            result <- doors
            true
        | _ -> false
    member this.TryGetLorry( [<Out>] result : double byref ) =
        match this with
        | Lorry weight ->
            result <- weight
            true
        | _ -> false

Now the experience is much better from C#:

int doors;
double weight;
if ( vehicle.TryGetCar( out doors ) )
{
    driveCar( doors );
}
else if ( vehicle.TryGetLorry( out weight ) )
{
    driveLorry( weight );
}

and the new methods are usable from F# as well, although you’d probably prefer to use match:

// Use TryGet approach - returns bool, int
let isCar, doors = vehicle.TryGetCar()

// Use match approach - more natural for F#
match vehicle with
| Car doors -> driveCar(doors)
| Lorry weight -> driveLorry(weight)

Leave a comment

Filed under F#, Programming

How to use the Digital Crown in a Watch Face App

I’ve written before that, having lived with the Apple Watch for a while, I felt the watch faces lacked variety. So, I wrote a watch face app, which I now use for the majority of the time.

For my next watch face, I thought it would be pretty cool to recreate the look of my beloved Tissot watch. One of its best features is that extra functionality is controlled by twisting/pressing the bezel. It supports date/time/stopwatch/timer – or you can hide the digital display altogether. Although WatchKit doesn’t allow you to capture a button press, you can use the digital crown to scroll between choices – so I thought I’d offer a couple of date formats as well as the option to hide the date altogether. tissot

Add a Picker control onto your storyboard and connect it to a WKInterfacePicker in your InterfaceController. There are a number of styles that you can choose, but for my purposes, I chose the default List style:
screen-shot-2017-01-12-at-19-09-55
Then it’s a matter of populating the picker’s list of items – for example, this code could go in function awake(withContext):

            let blankLine = WKPickerItem()
            blankLine.title = ""
            
            let currentDate = Date()
            let dayDateMonthLine = WKPickerItem()
            dayDateMonthLine.title = "\(currentDate.dayOfWeek()) \(currentDate.dayOfMonth()) \(currentDate.monthAsString())"
            let dateMonthYearLine = WKPickerItem()
            dateMonthYearLine.title = "\(currentDate.dayOfMonth()) \(currentDate.monthAsString()) \(currentDate.year())"
            
            InfoPicker.setHidden( false )
            InfoPicker.setItems( [ blankLine, dayDateMonthLine, dateMonthYearLine, blankLine ] )
            InfoPicker.focus()

I set the focus on the picker so that the digital crown is immediately responsive (otherwise, you’d have to select the picker first on the touch screen). I also put a blank line before and after the date formats, to make the usage more natural. The code above also uses some extension methods on Date.

Tissot style watch face

Seeing how good this looks, I think Apple are missing a trick. All of their analogue Apple Watch faces are round – I hope they ship a couple of rectangular faces in the next Watch OS upgrade.

2 Comments

Filed under Programming, Swift