Continuation of Andrei’s first talk.
C++ functions are a good method for abstraction, but there is no purity, safety or exceptions, these are covered by conventions.
Example: find an item in an array and do something with it. A nice way to implement this, is with a find and a work function. Searching details are separated form work details, so we have modularity and it can be applied to many different topologies.
The find function can be improved by taking a number (say 4) of values at one time and searching in them. This will, in modern C++, be executed simultaneously. The compiler can do this unrolling for simple cases, but not for all, and Andrei states that it is not a good idea to relay on the compiler for optimization.
Abstraction can also been done with classes, that are the basic unit of encapsulation in C++. Conventional wisdom: methods are cool, free functions are “so 60s”. But! Free functions actually improve encapsulations, says Andrei. Also, they may be more general, decouple better and support conversions of their left-hand argument.
Andrei now shares a surprising fact
“Making a function a method should be your last, not first choice.”
Because it will have access to all the privates of the class. Suppose I want to have the size of an string. We could look at the pointers, but a nicer way is just using the public interface. This does not sound that surprising, but it is a good principle nonetheless.
The STL (according to Andrei “the best software library ever conceived”) focuses on finding the essence of algorithms and answers the important question “how do I implement the fundamental version of all algorithms?”. For instance for QuickSort, we need random access, this is why it is not ideal for functional programming.
STL has 5 different iterators: input, output, forward, bidirectional, random access.
Homework question (answers may be posted in the comments :)) What iterators do you need for stable (items should stay in order) and unstable (order of remaining elements does not matter) remove?
It is efficient, has abstraction power and plays perfectly into C++ strength. Disadvantages are the lack of lambda functions that makes many algorithms tenuous, the syntax is relatively verbose and it is hard to understand from outside of the C++ community.
Recall the optimization from above, where we take 4 elements at once to search. How do we do this on linked lists? We would make a base implementation, just a number for loop, but we add a argument for the type and use a dispatcher to select the version the goes with the type of the iterator.
Before this lecture I was unsure what to expect, having no experience in C++ at all, but it was actually a great and funny talk that was easy to understand even for those with no C++ knowledge at all. Loved it!
More C++ and some D tomorrow, will be a great day again.