Rust for C++

Closures ( | | )

Captures

Borrow

Rust
let closure = || {println!("n: {:?}", block.number); };

Run

C++
auto closure = [&block]{ cout << "n: " << block.number << endl; };

Run

Move

Rust
let closure = move || {println!("n: {:?}", block.number); };

Run

C++
auto closure = [block=std::move(block)]{ cout << "n: " << block.number << endl; };

Run

Dispatch

Static

Rust
fn static_dispatch<T>(closure: &T)
    where T: Fn()->i32 {
    println!("static_dispatch: {:?}", closure());
}

Run

C++
template <typename T>
void static_dispatch(const T &callback) {
    cout << "static_dipatch: " << callback() << endl;
}

Run

Dynamic

Rust
fn dynamic_dispatch(closure: &Fn() -> i32) {
    println!("dynamic_dispatch: {:?}", closure());
}

Run

C++
void dynamic_dispatch(const function<int()> &callback) {
    cout << "dynamic_dispatch: " << callback() << endl;
}

Run

Storage

Rust
struct Block {
    callback: Box<Fn() -> i32>
}

Run

C++
struct Block {
    function<int()> callback;
};

Run