C++, Go, Julia, Rust

Florian Rappl, MVP Visual C#

C++, Go, Julia, Rust

... and Why Should I Care?!

New Wave Of Programming Languages

Florian Rappl

Writer and consultant

  • Microsoft C# MVP and CodeProject MVP
  • Active contributions to open-source projects
  • Company workshops, talks and IT consulting

Languages and technologies

  • C#, JavaScript and C/C++
  • Full web stack (client and server)
  • High Performance and Embedded Computing

Agenda

  1. A New Wave of Programming Languages
  2. Highlights and Examples
  3. Modern C++: What's Different?
  4. Lots of Examples and Coding
  5. C# vs. C++ - When to Use What?
A New Wave Programming Languages

New Languages

  • Julia
  • Go
  • Rust
  • Swift
  • D
  • (Modern) C++

Other (interesting) Languages

  • Nim
  • Haskell
  • Clojure
  • Groovy
  • Lua
  • OCaml
Examples Julia Go Rust Swift D

Julia

  • JIT compiled
  • Inspired by C, Python, Matlab, Lua
  • Dynamic type system
  • Meta programming capabilities
  • Very fast execution speed
  • Concurrency integrated
  • Coroutines for lightweight threading
  • Integrated package manager

Example (1)

2 + 1im # => Complex{Int64}
2//3 # => Rational{Int64}
fib(n) = n > 2 ? fib(n - 1) + fib(n - 2) : n
@time fib(40) # measure execution time
code_native(fib, (Int32,)) # native code for Int32
2 < 3 < 2 # chained comparison
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
vector = [1, 2, 3, 5]
range = [1:5] # => 5-element Int64 Array: [1,2,3,4,5]
matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
a, b, c = (1, 2, 3) # create and unpack tuples
a, b = b, a # swap variables

Example (2)

type Tiger
  taillength::Float64
  coatcolor # not including a type annotation leads to `::Any`
end
tiger = Tiger(3.5, "red")
typeof(Tiger)
subtypes(Number)
abstract Cat
type Lion <: Cat # Lion is a subtype of Cat
  mane_color
  roar::String
end
Lion(roar::String) = Lion("green",roar)

Go

  • Main feature: Excluding most features
  • Mainly inspired by C - but safer
  • Cross-platform from the beginning
  • Type inference and fast compilation
  • Integrated package manager
  • Concurrency via message passing (channels)
  • Dependency less (independent) programs

Example

package main
import ("fmt")
func multiple(x, y int) (sum, prod int) {
	return x + y, x * y // multiple return values
}
func main() {
	var x int // declared only
	var fv1 float64 = 0.75 // initialized directly
	x = 3 // assign value
	y := 4 // define value
	sum, prod := multiple(x, y) // resolve multiple
	fmt.Println("sum:", sum, "prod:", prod)
}

Rust

  • A safe, concurrent, practical language
  • Mainly influenced by C#, C++, Go, Haskell
  • Memory safe, secure and fast applications
  • Type classes (traits)
  • Visually much like C++, however, logic different
  • Prevents null or dangling pointers
  • Used in Mozilla's Servo project

Example (1)

use std;
fn add2(x: i32, y: i32) -> i32 {
	x + y // implicit return (no semicolon)
}
fn main() {
	let x: i32 = 1; // immutable
	let mut y = 1; // mutable
	struct Point { x: i32, y: i32 } // C-like
	enum Optional<T> { SomeVal(T), NoVal }
    for i in 0u32..10 { // range
        print!("{} ", i); // printf Macro
    }
}

Example (2)

fn peep_inside_box(borrowed_int: &i32) {
    println!("This int is: {}", borrowed_int);
}
fn main() {
    let mut integer = 5i32;
    {
        let ref_to_integer = &_integer;// Borrow `integer`
        integer = 4; // Error - `integer` is frozen
    } // `ref_to_integer` goes out of scope
    integer = 4; // `integer` unfrozen
}

Swift

  • Successor for the Apple ecosystem
  • Only available on OSX - no other system supported
  • Ideas from Objective-C, C#, D, JavaScript
  • Takes much (e.g., numeric types) from Objective-C
  • Type inference
  • Option types
  • Uses LLVM for optimizations

Example

import UIKit
let π = 3.1415926 // unicode variable names
let piText = "Pi = \(π), 2 Pi = \(π * 2)" // string interpolation
var shoppingList = ["catfish", "water", "lemons"] // mutable array
func getGasPrices() -> (Double, Double, Double) { // multiple return
	return (3.59, 3.69, 3.79)
}
var suitValue: Suit = .Hearts // no need for repetition
extension Int { // extend built-in types
	var customProperty: String { return "This is \(self)" }
	func multiplyBy(num: Int) -> Int { return num * self }
}

D

  • "C++ without all the problems"
  • Follows C++, C#, Eiffel, Python
  • Extension methods integrated
  • Strong metaprogramming features
  • Single inheritence with interfaces and mixins
  • GC + manual memory management
  • No preprocessor
  • Integrated package manager (DUB)

Example

import std.stdio;
enum withAlgorithm = true;
static if (withAlgorithm == true) 
	import std.algorithm;

void main() pure nothrow @safe {
	ulong lines = 0;
	double sum = 0;
	foreach (line; stdin.byLine()) {
		++lines;
		sum += line.length;
	}
}
Modern C++

C++ in a Single Slide

  • Not a superset of C, but close
  • Powerful operator overloading
  • Manual memory management
  • Abstracts resource management
  • Flexible algorithms with optimized data structures
  • Allows efficient stack-based programming
  • Includes its own meta-programming language

Federation of Languages

  1. C
  2. OOP
  3. TMP
  4. STL

Multi-Paradigm Language

  • Procedural
  • Generic
  • Functional
  • Object-Oriented
  • Freedom of choice can be a burden!

C++ Types

Types C# JavaScript Modern C++
Value
struct Val { }
class Val { };
Reference
class Foo : Base { 
	public override void Bar() { } 
}
class Foo : public Base { 
	public: void bar() override { } 
};
Interface
interface IFoo { 
	int Bar(); 
}
class IFoo { 
	public: virtual int bar() = 0; 
};
Generic
class Map<TKey, TValue> { }
template<class TKey, class TValue>
class Map { };
Optional
Nullable<int> i = 10;
var i = 10;
boost::optional<int> i = 10;
Dynamic
dynamic x = "str";
x = 10;
var x = "str";
x = 10;
boost::any x = "string";
x = 10;

History

Modern C++

  • Introduces helpful annotations
  • More complete STL
  • Express ownership
  • Elegant constructs
  • Less typing
  • Better performance
  • Easier to read and write

Comparison with C#

  • Iterators and iterator loops
  • Type inference
  • Lambda expressions
  • Sealing and explicit overrides
  • Async-like concurrency
  • UTF-16 string literals
  • Reference counted memory management

Enumerations

// C-style without safety
enum Suit { Diamonds, Hearts, Clubs, Spades };
Suit good_hand = Clubs;
int other_type = Hearts;
Suit bad_hand = 1;//won't compile, thankfully

// Modern C++ with type-safety
enum class Suit { Diamonds, Hearts, Clubs, Spades };
Suit good_hand = Suit::Clubs;
int other_type = Suit::Hearts;//won't compile
Suit bad_hand = 1;//won't compile

Iterator Loops

#include <vector>

std::vector<double> values = { 1, 2, 3, 4, 5 };
std::vector<double> squares;

for (const auto value : values) {
	squares.push_back(value * value);
}

Lambda Expressions

#include <algorithm>
#include <functional>

std::function<double(double)> f = [](double x){ 
	return x * x; 
};

std::vector<double> values = { 1, 2, 3, 4, 5 };
std::vector<double> squares(values.size());
std::transform(values.begin(), values.end(), squares.begin(), f);

Concurrency

#include <thread>
#include <future>

auto future = std::async([&]() {
	return "Hello World";
});

auto consumer = std::thread([&]() {
	std::cout << future.get();
});

Predefined String Literals

const auto a = u8"I'm a UTF-8 string.";
const auto b = u"This is a UTF-16 string.";
const auto c = U"This is a UTF-32 string.";

Custom Literals

#include <string>

std::string operator "" _s(const char* ptr, size_t n) { 
	return std::string(ptr, n);
}

auto mychr = "Hello World!";//auto is char*
auto mystr = "Hello World!"_s;//auto is std::string

Compile-Time Tuples

#include <tuple>

std::tuple<int, int, std::string> vals = std::make_tuple(1, 3, "Foo");

int first = get<0>(vals);
int second = get<1>(vals);
std::string third = get<2>(vals);

get<2>(vals) = "Bar";
Examples Coding Showcase

RNG

  • Random Number Generators

EBO

  • Empty Base Optimization

RAII

  • Resource Acquisition Is Initialization

RCSP

  • Reference Counting Smart Pointer

PIMPL

  • Pointer to IMPLementation idiom

SFINAE

  • Substitution Failure Is Not An Error
Comparison Versus C# C++
Miguel de Icaza
Choosing C++ is a case of premature optimization.

Miguel de Icaza
Xamarin CTO

General Considerations

  • Productivity is not so different any more
  • Use C++ if high performance is needed
  • Use C# to get a more dynamic runtime
  • C# may be better in cross-platform situations
  • C++ also works in memory constraint areas
  • GUI is (usually) abstracted anyway, so don't worry here

Language Details

  • C++ is about binary compatibility
  • C# is about meta reliability
  • No included reflection in C++
  • Huge difference: Templates vs generics
  • Looking for a REPL? Try Cling!
  • Compiler choice in C# is easy - for C++ not

Disadvantages

  • C++ requires more experience
  • In general the programmers need to be much better
  • Performance can be much better, but the opposite happens also
  • Binary compatibility enforces recompilation
  • No big standard framework
  • Bugs and exploits are more dangerous
  • Compilers have big differences (mostly implementation)

Disadvantages

Decision Matrix

C++ C#
LINQ Via Operators Extension methods
Reflection Extensive preprocessor Integrated
Inheritence Multiple, FCoI, NVI Single-base, Interfaces
Functional Lambdas, Closures Lambdas, Closures
Meta TMP, Preprocessor PostSharp (AoP), T4
Memory Stack, Heap (opt. RCSP, GC) Stack, GCed Heap

C++ in C#

  • Multiple ways
    • PInvoke (high error rate)
    • Wrapping in C++/CLI (productive and flexible)
    • Wrap in a COM object (less productive)
    • Mono/CppSharp (damn easy wrapping!)
  • Usually high call costs
  • Only worth it in certain scenarios
  • Very good domain boundary

Conclusions

  • C++ is a lot of fun
  • C++ is easier than ever
  • C++ is faster than ever
  • C++ might even be a better choice for a future project
  • Using it as a companion is very useful
  • However, programmers need to be very disciplined
Bjarne Stroustrup
There are only two kinds of languages: the ones people complain about and the ones nobody uses.

Bjarne Stroustrup
Created C++

Thanks for your attention

  • Feel free to contact me