CS253: Software Development with C++

Spring 2020

Bind

Show Lecture.Bind as a slide show.

CS253 Bind

Credit

Bind example from https://cplusplus.com/reference/functional/bind/

Overview

We’re going to describe a function called bind(), from <functional>, which takes as arguments a function and parameters, and yields as its result another function.

It can certainly be argued that lambda-functions are nearly a replacement for bind(), but ofttimes bind() expresses intention better, and is shorter.

Sans bind()

Let’s write a traditional function five():

double divide(double x, double y) {
    return x/y;
}

double five() {
    return divide(10, 2);
}

int main () {
    cout << "355 ÷ 113 = " << divide(355, 113) << '\n';
    cout << "10 ÷ 2 = " << five() << '\n';
}
355 ÷ 113 = 3.14159
10 ÷ 2 = 5

I like the traditional symbol “÷” for division.

bind()

Instead of a separate five() function, let’s use bind():

double divide(double x, double y) {
    return x/y;
}

int main () {
    auto five = bind(divide, 10, 2);
    cout << "10 ÷ 2 = " << five() << '\n';
}
10 ÷ 2 = 5

five() is equivalent to divide(10, 2).

bind()

double divide(double x, double y) {
    return x/y;
}

int main () {
    // Declare _1, _2, _3, …
    using namespace std::placeholders;
    auto half = bind(divide, _1, 2);
    cout << "12.4 ÷ 2 = " << half(12.4);
}
12.4 ÷ 2 = 6.2

half(d) is equivalent to divide(d, 2).

bind()

double divide(double x, double y) {
    return x/y;
}

int main () {
    using namespace std::placeholders;
    auto revdiv = bind(divide, _2, _1); // returns y/x
    cout << "5 ÷ 4 = " << revdiv(4, 5) << '\n';
}
5 ÷ 4 = 1.25

revdiv(a, b) is equivalent to divide(b, a).

bind()

double divide(double x, double y) {
    return x/y;
}

int main () {
    using namespace std::placeholders;
    auto invert = bind(divide, 1.0, _1); // 1/x
    cout << "1 ÷ 3 = " << invert(3.0) << '\n';
}
1 ÷ 3 = 0.333333

invert(d) is equivalent to divide(1.0, a).

λ

Or, just use a lambda-function:

double divide(double x, double y) {
    return x/y;
}

int main () {
    auto invert = [](double d) {return divide(1.0, d);};
    cout << "1 ÷ 3 = " << invert(3.0) << '\n';
}
1 ÷ 3 = 0.333333