C++11 bind

Source: Internet
Author: User

#include <iostream>#include<functional>using namespacestd;intFuncintAintb) {    returnA +b;}classfoo{ Public:    intFuncintAintb) {returnA +b; }};intMain () {Auto Bf1= Std::bind (func,Ten, std::p laceholders::_1); cout&LT;&LT;BF1 ( -) <<Endl;    Foo F; Auto BF2= Std::bind (&Foo::func, F, std::p laceholders::_1, std::p laceholders::_2); cout&LT;&LT;BF2 ( -, -) <<Endl; Std::function<int(int) > BF3 = Std::bind (&foo::func, F, std::p laceholders::_1, -); cout&LT;&LT;BF3 ( -) <<Endl; return 0;}

Bind is a mechanism that can pre-bind certain parameters of a specified callable entity to an existing variable, producing a new callable entity that is useful in the use of a callback function.

Example: Bf1 is a two-parameter common function of the first parameter is bound to 10, generated a new parameter of the callable body; BF2 is to bind a class member function to a class object and generate a new callable entity like a normal function; BF3 is to bind the class member function to the class object and the second parameter, resulting in a new Std::function object. To understand the above example, here are some things to note about using bind:

    • (1) Bind pre-bound parameters need to pass specific variables or values in, for the pre-bound parameters, is Pass-by-value
    • (2) For non-binding parameters, need to pass std::p laceholders go in, starting from the _1, in turn, increment. Placeholder is pass-by-reference.
    • (3) The return value of BIND is a callable entity and can be assigned directly to the Std::function object
    • (4) for binding pointers, arguments of reference types , the consumer needs to ensure that these parameters are available before callable entity calls
    • (5) The This of a class can be bound by an object or a pointer

C++11 bind

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.