C++11 Std::bind Std::function Advanced methods of Use

Source: Internet
Author: User

From the most basic understanding, Std::bind and Std::function

/* * File:main.cpp * author:vicky.h * Email: [email protected] */#include <iostream> #include <function al> #include <typeinfo> #include <string.h>int add1 (int i, int j, int k) {return i + j + k;}    Class Utils {public:utils (const char* name) {strcpy (_name, name); } void SayHello (const char* name) const {std::cout << _name << "Say:hello" << name &lt    ;< Std::endl;    } static int getId () {return 10001;    } int operator () (int i, int j, int k) const {return i + j + k; } Private:char _name[32];};/     * * */int main (void) {//bind global function Auto ADD2 = Std::bind (ADD1, std::p laceholders::_1, std::p laceholders::_2, 10); function add2 = bind add1 function. The number of participants is unchanged 1, and the number of 2 is unchanged.    The number of references 3 is fixed to 10.    Std::cout << typeid (ADD2). Name () << Std::endl;        Std::cout << "Add2" = "<< add2 (1, 2) << Std::endl; Std::cout << "\ n---------------------------" <<Std::endl;    The binding member function Utils Utils ("Vicky");    Auto SayHello = Std::bind (&utils::sayhello, utils/* caller */, std::p laceholders::_1/* reference 1*/);        SayHello ("Jack");    Auto Sayhellotolucy = Std::bind (&utils::sayhello, utils/* caller */, "Lucy"/* fixed parameters 1*/);        Sayhellotolucy ();    Bind static member function Auto GetId = Std::bind (&utils::getid);        Std::cout << getId () << Std::endl;        Std::cout << "\ n---------------------------" << Std::endl; Bind operator function Auto add100 = Std::bind (&utils::operator (), Utils, std::p laceholders::_1, std::p laceholders::_2, 1    00);        Std::cout << "add100 (1, 2) =" << add100 (1, 2) << Std::endl; Note: You cannot use Std::bind () to bind an overloaded function return 0;}


/* * File:main2.cpp * author:vicky.h * Email: [email protected] */#include <iostream> #include <typeinf O>void SayHello () {std::cout << "Hello world!" << Std::endl;} int sum (int i, int j, int k) {return i + j + k;}        Template <typename t>class Func {public:func (T fun) {if (!fun) {throw ' fun nullptr ';    } _fun = fun; } template<typename R, TypeName A1, TypeName A2, TypeName A3, TypeName A4, TypeName a5> R Call (A1 A1, A2 A2, A    3 A3, A4 A4, A5 a5) {return _fun (A1, A2, A3, A4, A5); } template<typename R, TypeName A1, TypeName A2, TypeName A3, TypeName a4> R Call (A1 A1, A2 A2, A3 A3, A4 A4)    {return _fun (A1, A2, A3, A4); } template<typename R, TypeName A1, TypeName A2, TypeName a3> R Call (A1 A1, A2 A2, A3 A3) {return _fun    (A1, a2, A3); } template<typename R, TypeName A1, TypeName a2> R Call (A1 A1, A2 A2) {return _fun (A1, A2);    } template<typename R, TypeName a1> R Call (A1 A1) {return _fun (A1);    } template<typename r> R call () {return _fun ();    } void Call () {_fun (); }private:t _fun;}; #include <functional>template<typename R = void, TypeName ... Args>class Fn {public:fn (Std::function<r (Args ...)    > Fun): _fun {} R operator () (args ... args) {return _fun (args ...); }private:std::function<r (Args ...) > _fun;};/ * * Register the function with the object.    Calls directly through the object */int main (void) {func<void (*) () > Sayhellofunc (SayHello);    Sayhellofunc.call ();    Func<int (*) (int, int, int) > Sumfunc (SUM);    Std::cout << "sumfunc.call<int> (1, 2, 3):" << sumfunc.call<int> (1, 2, 3) << Std::endl;    Std::cout << "\ n---------------------------" << Std::endl;    Fn<> sayhellofn (SayHello);        Sayhellofn ();    fn<int, int, int, int> SUMFN (sum); Std::cout << "SUMFN(1, 2, 3): "<< SUMFN (1, 2, 3) << Std::endl;    Std::cout << "\ n---------------------------" << Std::endl; return 0;}

Hello World!
Sumfunc.call<int> (1, 2, 3): 6


---------------------------
Hello World!
SUMFN (1, 2, 3): 6


---------------------------

The example above is interesting and uses 2 different scenarios. A function is registered in an object/functor, and called directly by an object/functor function.
Examples are obvious. The 2nd scenario is better concise, and there is a clear inference to the pass-through that the compiler will cause failure when the number of parameters is incorrect.
Such a scheme would be able to use the member variables of a class directly as a function's argument, or, for example, I:
http://blog.csdn.net/eclipser1987/article/details/23926395
In this article, the script function class cannot be called directly. There is a good way to solve it. This I will then add.





#include <list> #include <functional>template<typename ... Args>class fns{private:std::list<std::function<void (Args ...) > > _calls;public:virtual ~fns () {_calls.clear ();} void Connect (Std::function<void (Args ...) > FCT) {_calls.push_back (FCT);} Template<typename object>void Connect (object* object, void (object::* method) (Args ...) {_calls.push_back ([Object,method] (args ... args) {(*object.*method) (args ...);}); Template<typename object>void Connect (object* object, void (object::* method) (Args ...) const) {_calls.push_back ( [Object,method] (args ... args) {(*object.*method) (args ...);}); Template<typename object>void Connect (const object* object, void (object::* method) (Args ...) const) {_calls.push_ Back ([Object,method] (args ... args) {(*object.*method) (args ...);}); void emit (args ... args) {for [Auto call: _calls] Call (args ...);};


#include <cstdio> #include "signal.hpp" Class foo{public:void bar (int x, int y) {printf ("Foo::bar (%d,%d) \ n", x, y);}} void Foobar (int x, int y) {printf ("foobar (%d,%d) \ n", x, y);} int main (void) {foo foo; Fns<int, int> s;//connect a functions.connect (foobar);//Connect a class Methods.connect (&foo, &foo::bar) ;//Create and connect some lambda expressions.connect ([&foo] (int x, int y) {printf ("Lambda::"); Foo.bar (x, y); });//Emit the signal!s.emit (4, 2); GetChar (); return 0;}

Foobar (4, 2)
Foo::bar (4, 2)
Lambda::foo::bar (4, 2)




C++11 Std::bind Std::function Advanced methods of Use

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.