std::bind in C++ – Explained with Examples

In this article, we’ll explore the std::bind function from the C++ Standard Library, learn how it acts as a functional adaptor, and understand its uses with examples.

What is std::bind?

The std::bind function is part of the Standard Function Objects and is a versatile tool used for creating new function objects by binding arguments to a given function. It essentially “adapts” a function by fixing some of its arguments or rearranging them.

Binding Arguments with std::bind

Let’s begin by considering a simple function that adds two integers:

int add(int first, int second) {
    return first + second;
}

Using std::bind, you can create a new function object that behaves like add:

auto add_func = std::bind(&add, _1, _2);

Here, add_func now represents a function object that can be called with two arguments, just like add. The _1 and _2 are placeholders from the std::placeholders namespace, which are replaced by the arguments passed to add_func:

std::cout << add_func(4, 5); // This will output 9

Binding and Rearranging Arguments with std::bind

Suppose we have a situation where the first argument to add should always be 12, and the second argument should be specified at call time:

auto new_add_func = std::bind(&add, 12, _1);

Calling new_add_func(5) will internally call add(12, 5):

std::cout << new_add_func(5); // Outputs 17

So, when we call new_add_func(5), it will internally call the add() function with the first parameter always being 12 and the second parameter being 5, which is passed as an argument. It will return 17.

What if you want to rearrange the arguments? std::bind allows you to do that too:

auto mod_add_func = std::bind(&add, _2, _1);

_1 represents the first passed argument and _2 the second passed argument. Now, while constructing a new function object through std::bind, we changed the order of arguments by passing _2 first and _1 second in the underlying function.

Now, mod_add_func(12, 15) will call add(15, 12):

std::cout << mod_add_func(12, 15); // Outputs 27

Using std::bind with STL Algorithms

One of the strengths of std::bind is its ability to simplify the use of STL (Standard Template Library) algorithms by adapting function signatures. Consider the following function that checks if one number is divisible by another:

bool divisible(int num, int den) {
    return num % den == 0;
}

This function takes two arguments and checks if num is divisible by den. To adapt this function to work with std::count_if, you need a unary predicate—a function that takes a single argument.

First Approach: Manual Loop

The first approach manually iterates over each element in the array and applies the divisible function:

int approach_1() 
{
    int arr[10] = {1, 20, 13, 4, 5, 6, 10, 28, 19, 15};
    int count = 0;
    for (int i = 0; i < sizeof(arr)/sizeof(int); i++) 
    {
        if (divisible(arr[i], 5))
            count++;
    }
    return count;
}

Second Approach: Using std::count_if with std::bind

The second approach simplifies the code by using std::count_if along with std::bind to create a function object that checks if a number is divisible by 5:

int approach_2() 
{
    int arr[10] = {1, 20, 13, 4, 5, 6, 10, 28, 19, 15};
    auto is_divisible_by_5 = std::bind(&divisible, std::placeholders::_1, 5);

    return std::count_if(arr, arr + sizeof(arr)/sizeof(int), is_divisible_by_5);
}

In the code above, std::bind(&divisible, std::placeholders::_1, 5) creates a new function object that takes one argument and checks if it’s divisible by 5. This is possible because std::placeholders::_1 acts as a placeholder for the argument that std::count_if will pass to the predicate.

When std::count_if is called, it will iterate over the array and apply the is_divisible_by_5 predicate to each element. This approach is cleaner and leverages the power of the C++ Standard Library to write less and do more.

It’s worth noting that with C++11 and later, you can achieve similar functionality using lambda expressions, which are often more readable and inline with modern C++ practices:

int approach_3() 
{
    int arr[10] = {1, 20, 13, 4, 5, 6, 10, 28, 19, 15};
    return std::count_if(std::begin(arr), std::end(arr), [](int value) { return divisible(value, 5); });
}

This version does not require std::bind at all, making it simpler and possibly more preferable for many C++ programmers.

What Does std::bind Return?

std::bind returns a callable function object. This object can be stored in an auto variable or used directly. Alternatively, it can be stored in a std::function object for later use:

std::function<int(int)> mod_add_funcObj = std::bind(&add, 20, _1);

Complete Example with std::bind

Here’s the complete code that demonstrates std::bind in action:

#include <iostream>
#include <functional>
#include <algorithm>

// For placeholders _1, _2, ...
using namespace std::placeholders;

int add(int first, int second) {
    return first + second;
}

bool divisible(int num, int den) {
    return num % den == 0;
}

int main() {
    // Demonstrating binding and rearranging
    auto new_add_func = std::bind(&add, 12, _1);
    std::cout << new_add_func(5) << std::endl; // Outputs 17

    auto mod_add_func = std::bind(&add, _2, _1);
    std::cout << mod_add_func(12, 15) << std::endl; // Outputs 27

    // Using bind with std::function
    std::function<int (int)> mod_add_funcObj = std::bind(&add, 20, _1);
    std::cout << mod_add_funcObj(15) <<

 std::endl; // Outputs 35

    // Counting multiples of 5 in an array
    int arr[10] = {1, 20, 13, 4, 5, 6, 10, 28, 19, 15};
    auto divisible_by_5 = std::bind(&divisible, _1, 5);
    int count = std::count_if(arr, arr + sizeof(arr)/sizeof(int), divisible_by_5);
    std::cout << count << std::endl; // Outputs number of elements divisible by 5

    return 0;
}

Output:

17
27
35
4

Summary

std::bind is a powerful feature in C++ that allows you to create custom callable objects from existing functions by fixing certain arguments or changing their order. This can be particularly useful when working with STL algorithms that expect specific function signatures. With std::bind, complex tasks that involve functions can be made simple and concise, improving both the readability and flexibility of your code.

3 thoughts on “std::bind in C++ – Explained with Examples”

  1. Rajendra Chandravanshi

    in approch2 std::placeholders::_1 is required

    int approch2()
    {
    std::array arr = {1,20,13,4,5,6,10,28,19,15};
    return std::count_if(arr.begin(), arr.end(), std::bind(&divisible, std::placeholders::_1, 5));
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top