function pointers, Function,bind, lambda

Source: Internet
Author: User

function pointers, Sd::function<type1, type2...> Functionobject, Std::bind ()


1. Function pointers are not type-safe, why?

#include <stdio.h>int max (int x,int y) {return (x>y? x:y);} int main () {    int (*ptr) (int, int);    int A, B, C;    ptr = max;    scanf ("%d%d", &a, &b);    c = (*ptr) (A, b);    printf ("a=%d, b=%d, max=%d", A, B, c);    return 0;}


The C language function pointer is an address variable that does not have any type checking at the time of assignment or invocation.

Any function pointer can be transformed to another type of function pointer, which is the same as the original function pointer when it is transformed back.

It is up to the programmer to remember exactly what type it is.

The transformation is wrong, cast is finished.

This is the type that is unsafe.


The function pointer cannot give the compiler an error prompt in advance. This is in


2. Std::function

Put a function in a function object

#include < functional> std::function< size_t (const char*) > Print_func; normal function-std::function objectsize_t cprint (const char*) {...} Print_func = Cprint;print_func ("Hello World"):
The following effects are the same//====================///functor, std::function objectclass cxxprint{public:    size_t operator () ( Const char*) {...}}; Cxxprint P;print_func = P;print_func ("Hello World");

function<float (int x, int y) > F; Constructs a function object that can represent a function with a return value of float, two parameters of Int,int

Type checking is performed on the parameter types of the function to ensure type safety.


3. Std::bind

Binding a variable or value to a function parameter, for a pre-bound parameter, is Pass-by-value

#include < functional>intFunc(intXintY);AutoBf1=Std::Bind(Func,Ten, STD::placeholders::_1);Bf1( -); ///< Same as Func (Ten)

after the std::bind is bound, it can be assigned to an auto variable or to a Function object. Auto automatic type definition.
A A;AutoBf2=Std::Bind(&A::Func, A, STD::placeholders::_1, STD::placeholders::_2);Bf2(Ten, -); ///< Same as A.func (Ten)Std::function< int(int)>Bf3=Std::Bind(&A::Func, A, STD::placeholders::_1, -);Bf3(Ten); ///< Same as A.func (Ten)

1. For non-binding parameters, std::p laceholders go in, start from _1, and then increment. Placeholder is pass-by-reference.

2. The return value of BIND is a callable entity and can be assigned directly to the Std::function object

3. Bind guarantees type safety, but for the content of bound variables, the programmer is guaranteed to be effective


4. Lambda

For implementing an anonymous function, the biggest use is to callback the callback function.

Example 1:

Vector< int>Vec;/// 1. Simple LambdaAutoIt=Std::find_if(Vec.begin()Vec.End(),[](intI) { returnI>  -; });

The effect is equivalent to a function object.


Can have a return value, if the capture context, you can use an external local variable, or a class member variable

/// 2. Lambda expr:capture of local variable{    intMin_val= Ten;    intMax_val=  +;AutoIt=Std::find_if(Vec.begin()Vec.End(),[=](intI) {        returnI>Min_val&&I<Max_val;         });}

[=], [&],

= The variable pass-by-value for capture, the second small to take out a & to represent the variable of capture pass-by-reference


When using function, when the parameters are many, bind will pass in many std::p laceholders, and it is not intuitive to look at lambda expressions, so it is generally recommended to use lambda expressions first.


Reference study:

http://www.wuzesheng.com/?p=2032

function pointers, Function,bind, lambda

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.