Using the function object using the detailed

Source: Internet
Author: User

The template class function is a common polymorphic function wrapper whose instances can store, copy, and invoke any callable object-functions, lambda expressions, expressions, and bind other function objects. It can also be a pointer to a member function pointer or a data member.

An empty function instance call will throw an std::bad_function_call exception.

#include <iostream>#include <functional>int main(){    std::function<intnullptr;    try {        f();    catch(conststd::bad_function_call& e) {        std::cout‘\n‘;    }}

Example code:

#include <functional>#include <iostream>structFoo {foo (intnum): num_ (num) {}voidPrint_add (intIConst{STD::cout<< Num_+i <<' \ n '; }intNum_;};voidPrint_num (inti) {STD::cout<< I <<' \ n ';}structPrintnum {void operator()(intIConst{STD::cout<< I <<' \ n '; }};intMain () {//Store a free function    STD::function<void(int) > F_display = print_num; F_display (-9);//Store a lambda    STD::function<void() > F_display_42 = [] () {Print_num ( the);    }; F_display_42 ();//Store The result of a call to Std::bind    STD::function<void() > f_display_31337 =STD:: Bind (Print_num,31337); f_display_31337 ();//Store a call to a member function    STD::function<void(ConstFoo&,int) > F_add_display = &foo::p rint_add;ConstFoo Foo (314159); F_add_display (foo,1);//Store a call to a member function and object    using STD::p laceholders::_1;STD::function<void(int) > F_add_display2=STD:: Bind (&foo::p rint_add, Foo/ * Caller /*, _1); F_add_display2 (2);//Store a call to a member function and object ptr    STD::function<void(int) > f_add_display3=STD:: Bind (&foo::p rint_add, &foo/ * Caller /*, _1); F_add_display3 (3);//Store a call to a function object    STD::function<void(int) > F_display_obj = Printnum (); F_display_obj ( -);}

Using the function object using the detailed

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.