To master C's std::function and std::bind, the key is to understand its core uses and use them reasonably. 1. std::function is used to uniformly store various callable objects, such as ordinary functions, lambda expressions or functions that bind parameters, and can be loaded as long as the signature is consistent; 2. std::bind is used to fix parameters or adjust the call order, and reserve subsequent parameter positions through placeholders \_1 and \_2; 3. The combination of the two can be used in event callbacks, task queues and other scenarios to improve interface flexibility; 4. When using it, you need to pay attention to the clear object life cycle and parameter order and avoid excessive complexity, and give priority to lambda to keep the code concise.
If you want to use C's std::function
and std::bind
clearly, it is actually not that mysterious. Their core function is to help you "wrap" functions, member functions, and calls with parameters, and unify them into an object that can be flexibly passed and called. Let’s start with a few actual situations and see how to use them.

How to store various callable objects with std::function
?
std::function
is like a general "function box". It can be installed no matter whether you are a normal function, a lambda expression, or a function with parameters bound. for example:

#include <functional> #include <iostream> void hello() { std::cout << "Hello, world!" << std::endl; } int main() { std::function<void()> f = hello; f(); // Output Hello, world! }
You can also assign a lambda to it:
std::function<int(int, int)> add = [](int a, int b) { return ab; }; std::cout << add(3, 4) << std::endl; // Output 7
The key point is: as long as the signature matches (the return type and parameter list are the same), std::function
can be installed.

How to use std::bind
to fix parameters or adjust the order?
Sometimes you want to call a function, but its parameter order is not very appropriate, or you want to fix some parameters in advance. At this time, you can use std::bind
to "preset" some content.
For example:
#include <functional> #include <iostream> void print_sum(int a, int b) { std::cout << ab << std::endl; } int main() { auto f = std::bind(print_sum, 2, 3); f(); // Output 5 }
In the example above, we fixed both parameters. If you want to fix one of them and leave a subsequent pass, you can use the placeholder _1
(defined in std::placeholders
):
auto f = std::bind(print_sum, 10, std::placeholders::_1); f(5); // Output 15
A few points to note:
-
_1
is the position of the first parameter,_2
is the second, and so on. - If you are bound to a member function, remember to pass
this
or object pointer as the first parameter.
Use std::bind
and std::function
more flexible
These two are particularly suitable for event callbacks and task queues, where delayed execution or unified interface is required. for example:
#include <functional> #include <vector> #include <iostream> void call_later(std::function<void()> cb) { cb(); } struct Foo { void bar(int x) { std::cout << "bar called with " << x << std::endl; } }; int main() { Foo foo; auto cb = std::bind(&Foo::bar, &foo, 42); call_later(cb); // Output bar called with 42 }
The key here is: std::bind
binds the member function into a normal callable object, and then receives it uniformly through std::function<void></void>
. This pattern is common in GUI programming or asynchronous programming.
Pay attention to a few places that are easy to get stuck
- Be careful about the object life cycle when binding : If you bind an object's reference or pointer, the object cannot be destructed in advance, otherwise an error will occur during the call.
- If there are too many binding parameters, it is easy to confuse the order : especially when nesting binds, it is recommended to write clearly the source of each parameter.
- Avoid overuse : While
bind
is powerful, lambdas are usually clearer and concise, and unless you need to reuse the binding logic, lambdas are preferred.
Basically that's it. Once you have used it well, you will find that the combination of std::function
and std::bind
can indeed solve many problems of inconsistent interfaces, but don't use it too complicatedly, otherwise it will be a headache for debugging.
The above is the detailed content of C std::bind and std::function tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The main difference between Java and other programming languages ??is its cross-platform feature of "writing at once, running everywhere". 1. The syntax of Java is close to C, but it removes pointer operations that are prone to errors, making it suitable for large enterprise applications. 2. Compared with Python, Java has more advantages in performance and large-scale data processing. The cross-platform advantage of Java stems from the Java virtual machine (JVM), which can run the same bytecode on different platforms, simplifying development and deployment, but be careful to avoid using platform-specific APIs to maintain cross-platformity.

Reducing the use of global variables in C can be achieved by: 1. Using encapsulation and singleton patterns to hide data and limit instances; 2. Using dependency injection to pass dependencies; 3. Using local static variables to replace global shared data; 4. Reduce the dependence of global variables through namespace and modular organization of code.

In C, the bit field is a structure member that specifies the number of bits, used to save memory and directly manipulate hardware. Example: structMyStruct{inta:2;intb:5;intc:1;}. The advantage of bit domains is memory savings, but there are cross-platform issues, access restrictions and assignments that require caution. Example of usage: structStateMachine{unsignedintpower:1;unsignedintmode:2;unsignedinterror:1;}. Performance recommendations include arranging bit fields by size, avoiding overuse and adequate testing.

The syntax of the trigonometric operator in C is condition?expression1:expression2, which is used to select and execute different expressions according to the condition. 1) Basic usage example: intmax=(x>y)?x:y, used to select the larger value in x and y. 2) Example of nested usage: intresult=(a>0&&b>0)?a b:(a==0||b==0)?a*b:a-b, used to perform different operations according to different conditions. 3) Error handling example: std::stringerrorMessage=(errorCode==0)?"Successful&quo

The usage of logical non-operator! in C includes: 1) Basic usage: inverse the Boolean value; 2) Conditional judgment: simplify the code, such as checking whether the container is empty; 3) Loop control: processing elements that do not meet the conditions; 4) Function return value processing: determine whether the operation has failed. Pay attention to potential pitfalls such as pointer processing and operator priority when using!, but it can help write more concise and efficient code.

Create a custom filter for cxImage in the Debian system. You can use the following steps: Prepare to install the cxImage library: Confirm that the cxImage library is installed. If it has not been installed, please use the following command to install: sudoapt-getupdatesudoapt-getinstalllibcximage-dev Install the development tool: Some development tools need to be installed to compile C/C code: sudoapt-getinstallbuild-essential Write custom filter creation filter code: Create a new C/C file, such as custom_filter.cpp

In the Debian system, you can follow the following steps: Installing the cxImage library First, make sure you have installed the cxImage library. If it has not been installed, you can install it through the following command: sudoapt-getupdatesudoapt-getinstalllibcximage-dev Write the code Next, write a simple C program to show how to use the cxImage library for image rotation. Here is a sample code: #include#includein

VSCode has become the preferred tool for C developers because of its flexibility, scalability and powerful debugging capabilities. 1. Install C/C ExtensionPack to provide syntax highlighting and code completion. 2. Configure the tasks.json file and use the g compiler to compile the code. 3. Create launch.json file and configure the GDB debugger for debugging.
