Open In App

Working and Examples of bind () in C++ STL

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the std::bind function is a part of the Standard Template Library (STL) and it is used to bind a function or a member function to a specific object or value. It creates a new function object by “binding” a function or member function to a specific object or value, allowing it to be called with a different number of arguments or with a different order of arguments.

Syntax:

std::bind(function, object/value, arguments...);

Parameters:

  • function: it is the member function that you want to bind. It can be a function pointer, a function object, or a member function pointer.
  • object/value: the object or value to which you want to bind the function. For member functions, this is the object on which the member function will be called. For free functions, this argument can be ignored.
  • arguments: are any additional arguments that should be passed to the function when it is called. These can include placeholders represented by std::placeholders::_1, std::placeholders::_2, etc, which can be used to specify where the arguments passed to the returned function object should be placed.

Return Value: The std::bind function in C++ returns a function object, also known as a “call wrapper” or “binder”, that is a bound version of the original function or member function. This function object can be invoked like a regular function, but with some of its arguments pre-bound to specific values or objects.

The return type of the std::bind function is a type that is dependent on the function or member function being bound, the arguments passed to the std::bind function, and the placeholders used to specify where the arguments passed to the returned function object should be placed.

Example: 

C++




// C++ Program to find a Greater
// number than a given number
#include <algorithm>
#include <functional>
#include <iostream>
 
using namespace std::placeholders;
 
// condition
bool greaterThan(int num, int limit) { return num > limit; }
 
// function to count greater than value
int countGreaterThan()
{
    int arr[15] = { 1, 5,  8, 9,  10, 3, 12, 6,
                    4, 15, 2, 20, 11, 7, 18 };
 
    // using binding
    return std::count_if(arr,
                         arr + sizeof(arr) / sizeof(int),
                         std::bind(&greaterThan, _1, 10));
}
 
// Driver Code
int main()
{
    std::cout << "Number of elements greater than 10: "
              << countGreaterThan() << std::endl;
    return 0;
}


Output

Number of elements greater than 10: 5

Time comple

In the above program, we have a function greaterThan which takes 2 parameters an integer and a limit, it returns true if the integer is greater than the limit.

The countGreaterThan function uses the std::count_if algorithm to count the number of elements in the array that are greater than 10. The condition is specified by passing a function object, which is created using the std::bind function, to the std::count_if function. The function object is a bound version of the greaterThan function that has its second argument pre-bound to the value 10. The first argument passed to the function object will be an element of the array.

Example: 

C++




// C++ Program to find
// the longer words
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
 
// condition
bool isLongerThan(std::string word, int limit)
{
    return word.length() > limit;
}
 
// function to count long words
int countLongWords()
{
    std::string words[]
        = { "apple",      "banana", "cherry", "date",
            "elderberry", "fig",    "grape""honeydew" };
 
    // using binding function
    return std::count_if(
        words,
        words + (sizeof(words) / sizeof(std::string)),
        std::bind2nd(std::ptr_fun(isLongerThan), 5));
}
 
// Driver Code
int main()
{
    std::cout
        << "Number of words longer than 5 characters: "
        << countLongWords() << std::endl;
    return 0;
}


Output

Number of words longer than 5 characters: 4

In the above program, we have a function isLongerThan which takes 2 parameters, a string, and an integer limit, it returns true if the length of the string is greater than the limit.

Exceptions

The std::bind function in C++ can throw an exception of type std::bad_function_call if the function or member function passed to it is not callable, for example, if it is a null pointer or an invalid function pointer. Additionally, the std::bind function can also throw an exception of type std::bad_alloc if there is not enough memory available to create the function object.

It is important to ensure that the function or member function passed to std::bind is callable and that there is enough memory available to create the function object before calling std::bind. Also, if the function or member function passed to the std::bind throws an exception, the function object returned by std::bind will propagate that exception to the caller when it is invoked.

Example:

C++




// C++ Program to Exceptions
#include <functional>
#include <iostream>
 
// function created
void myFunction()
{
    std::cout << "This function does something."
              << std::endl;
}
 
// Driver Code
int main()
{
    std::function<void()> func;
   
      // Normal condition
    try {
        func();
    }
      // Exception when binder created
    catch (std::bad_function_call& e) {
        std::cout << "Error: " << e.what() << std::endl;
    }
    return 0;
}


Output

Error: bad_function_call

In the above program, a std::function object named func is created and initialized to an empty function object.
Then, when func() is called, it throws an exception of type std::bad_function_call because it’s empty and it doesn’t point to any function.
The exception is caught by the catch block and the error message is printed to the console.

It is important to note that this error is thrown at runtime, so it is important to have proper error handling in place to catch and handle these exceptions. The type of exception that is thrown in this case is std::bad_function_call which is a derived class of std::exception which is a standard C++ exception.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads