Home > Backend Development > C++ > How does `std::bind` work with member functions in C ?

How does `std::bind` work with member functions in C ?

Barbara Streisand
Release: 2024-10-29 21:38:30
Original
834 people have browsed it

How does `std::bind` work with member functions in C  ?

Understanding std::bind with Member Functions

std::bind, a versatile tool in C , allows creating bound functions for later invocation. Understanding its usage with member functions can be challenging, but this discussion aims to shed light on the intricacies involved.

First Argument: A Pointer, Not a Reference

When declaring a binding for a member function, the first argument of std::bind is not a reference to the member function but rather a pointer to it. This is because functions and data members alike decay into pointers when passed as arguments.

Second Argument: Object or Pointer

The second argument of std::bind when dealing with member functions specifies the object or pointer to the object that will be used to invoke the member function. This is necessary because member functions have an implicit this pointer that points to the object they belong to.

Internal Implementation

Internally, std::bind appears to create a callable object that wraps the pointer to member function. When calling this bound function, the specified object is used as the this pointer.

Why a Pointer to the Object?

Unlike function pointers, which are independent of any specific object, member function pointers are tied to the class they belong to but can be used with any object of that class. std::bind supports this by requiring an object pointer as the second argument when dealing with member functions.

Example

Consider the following code:

<code class="cpp">struct Foo {
    void print_sum(int n1, int n2) { std::cout << n1 + n2 << '\n'; }
};

Foo foo;

auto f = std::bind(&Foo::print_sum, &foo, 95, _1);</code>
Copy after login

In this example, the first argument to std::bind is &Foo::print_sum, which is a pointer to the member function print_sum within the Foo class. The second argument is &foo, which is a pointer to the foo object. When invoking f, &foo is used as the this pointer, allowing print_sum to be called with the correct context on the foo object.

The above is the detailed content of How does `std::bind` work with member functions in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template