Callable Objects: Using std::function and std::bind

Share the Article

There are various ways to implement callback methods. Basically, the traditional way is to use function pointers or function references. However, C++11 introduces a notion of callable objects. These objects are generic function pointers. They include, not only function pointers and function references from C but also, lambdas, and functors.

Function Pointer

To start with, the following example illustrates the use of callback method using a simple function pointer. Here, “fp” is the type which denotes a function pointer. Such function must accept one integer argument and returns void type.

#include <iostream> //main header using namespace std; //namespace typedef void(*fp)(int); //fp is type pointer to function void funda(int xvar) { cout << "Function called with :" << xvar << endl; } void testCallBack(fp ptr, int arg) { ptr(arg); } int main() { testCallBack(funda, 4); return 0; }

Output

Function called with :4

Problem with function pointers

Function pointers are very rigid and they require exact types of parameter and return value. These function pointer can neither accept a non-static class member nor a functor.

The following program uses same function pointer but this time, the program passes a functor. Clearly, the compiler shall generate an error in this case.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace typedef void(*fp)(int); void funda(int xvar) { cout << "Function called with :" << xvar << endl; } class MainFunda { public: void operator()(int xvar) { cout << "Functor called with :" << xvar << endl; } }; void testCallBack(fp ptr, int arg) { ptr(arg); } int main() { testCallBack(funda, 4); // funda is function pointer MainFunda avar; testCallBack(avar, 5); // avar is functor return 0; }

The error message is:

In C++ typedef has problems when function objects passed

Callable Objects

These are like, generalized function pointers and they consist of anything which can be called like, a function. For example, lambda, functors, non-static member functions.

In C++11, a new template class std::function represents all such callable objects. This class is a type-safe wrapper for all the entities which we use just like function calls.

The following example, now defines “fp” as any callable object type which needs one integer parameter and returns void. We will see that this type now accept, not only function pointer but also lambda and functor.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace //typedef void(fp)(int); using fp = std::function<void(int)>; void funda(int xvar) { cout << "Function called with :" << xvar << endl; } class MainFunda { public: void operator()(int xvar) { cout << "Functor called with :" << xvar << endl; } }; void testCallBack(fp ptr, int arg) //Accepts callable objects { ptr(arg); } int main() { testCallBack(funda, 4); //funda is Function pointer MainFunda avar; testCallBack(avar, 5); //avar is functor auto lc = [](int xvar) { cout << "Lambda called with :" << xvar << endl; }; testCallBack(lc, 6); //lc is lambda return 0; }

The output is:

Function called with :4 Functor called with :5 Lambda called with :6

Comparing callable objects with nullptr

The function callable objects support comparison with nullptr. This is because, if nothing has initialised a callable object, then it essentially become like a null object.

The following example, creates 2 function objects f1 & f2. And only one of them is initialized (with lambda). The other one will become equivalent to nullptr.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespace //typedef void(fp)(int); using fp = std::function<void(int)>; void checkCallback(fp f) { if(f==nullptr) cout << "No callback assigned" << endl; else cout << "callback assigned" << endl; } int main() { auto lc = [](int xvar) { cout << "Lambda called with :" << xvar << endl; }; fp fvar1; //This callable object is empty fp fvar2 = lc; //This callable object is not empty checkCallback(fvar1); checkCallback(fvar2); return 0; }
No callback assigned callback assigned

Comparison of function callable objects not allowed

The std::function class do not allow comparison of two objects. Internally, the operator==( ) and operator!=( ) are deleted functions.

void compareCallbacks(fp fvar1, fp fvar2) //fp is callable { if(fvar1==fvar2) //error { } if(fvar1!=fvar2) //error { } }

Understanding the use of std::bind for callable objects

The function std::bind( ) also creates a callable object. Additionally, it maps the parameters of function objects with predefined values or with any of actual arguments passed in the call.

Bind the parameters with fixed values

The following function first creates a callable std::function object “fp” using a function pointer. And in second step, it uses bind to map parameter of this callable object with fixed values. Now, whenever, the callable object is called, it only uses mapped values.

#include <iostream> //main header #include <functional> //for function ptr using namespace std; //namespaces using namespace std::placeholders; void funda(int avar, int bvar, int cvar, int dvar) { cout << "\nfirst arg=" << avar << endl; cout << "second arg=" << bvar << endl; cout << "third arg=" << cvar << endl; cout << "fourth arg=" << dvar << endl; } int main() { std::function<void(int, int, int, int)> fp = funda; fp(1,2,3,4); //Before bind fp = std::bind(fun, 10, 20, 30, 40); fp(1,2,3,4); //After bind return 0; }

The output is:

first arg=1 => Before bind second arg=2 third arg=3 fourth arg=4 first arg=10 => After bind second arg=20 third arg=30 fourth arg=40

Using placeholders to map parameters with actual arguments

The nth argument passed to in actual call is denoted with “_n”. These actual arguments are denoted as placeholders. The placeholders can map any actual argument with any parameter of callable object.

For instance, the following example, there are 2 bind calls,

The previous call, maps second (_2) and fourth (_4) actual argument with corresponding parameters positions in the callable objects. And after that, the second bind function reverses that connection between second and forth mapping.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespaces using namespace std::placeholders; void funda(int avar, int bvar, int cvar, int dvar) { cout << "\nfirst arg=" << avar << endl; cout << "second arg=" << bvar << endl; cout << "third arg=" << cvar << endl; cout << "fourth arg=" << dvar << endl; } int main() { std::function<void(int, int, int, int)> fp = funda; fp(1,2,3,4); fp = std::bind(funda, 10, _2, 30, _4);//second to second //forth to forth fp(1,2,3,4); fp = std::bind(funda, 10, _4, 30, _2);//forth to second, //second to forth fp(1,2,3,4); return 0; }

The output is:

first arg=1 second arg=2 third arg=3 fourth arg=4 first arg=10 second arg=2 third arg=30 fourth arg=4 first arg=10 second arg=4 third arg=30 fourth arg=2

Application of std::bind( ) : Implementation of an Adaptor

The bind function can modify the mapping between actual arguments and the parameters of callable objects. Therefore, such feature helps in implementing an adaptor between 2 interfaces.

The following example, internally maps the inputs of a 2D object to corresponding inputs of a 3D object. Specifically, for completion, it maps the third parameter of 3D to a constant value. Finally, the 3D object’s draw becomes a callback for 2D object’s draw.

#include <iostream> //main header #include <functional>//for function ptr using namespace std; //namespaces using namespace std::placeholders; using cb2DType = std::function<void(int, int)>; class mainfunda2D { public: void setCallback(const cb2DType& cb) { drawCallback = cb; } void draw(int x, int y) { drawCallback(x,y); } private: cb2DType drawCallback; }; class mainfunda3D { public: void draw (int x, int y, int z) { cout << "Draw on (" << x << ", " << y << ", " << z << ")" << endl; } }; int main() { mainfunda2D _2d; mainfunda3D _3d; _2d.setCallback(std::bind(&mainfunda3D::draw, _3d, _1, _2, 50) ); _2d.draw(4,5); return 0; }

The output is:

Draw on (4, 5, 50)

Main Funda: C++11 callable objects are like, generic function pointers, they are are called like functions.

Related Topics:

 What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
Rule of Three
How std::move() function works?
What is reference collapsing?
How delete keyword can be used to filter polymorphism
emplace_back vs push_back


Share the Article

4,563 thoughts on “Callable Objects: Using std::function and std::bind

  1. Functions as an antioxidant: Ascorbic acid is a powerful antioxidant that counteracts oxidative stress in our bodies – normotim lithium ascorbate – shielding cells from harm caused by destructive molecules known as free radicals.

  2. Lithium, a trace element inherently found in particular foods and water – normopharm – has been scrutinized for its probable neuroprotective influences.

  3. Заменим или установим линзы в фары, ремонт фар – которые увеличат яркость света и обеспечат комфортное и безопасное движение на автомобиле.

  4. Online kazino ir kluvis par loti ietekmigu izklaides veidu visa pasaule, tostarp ari Latvijas teritorija. Tas nodrosina iespeju baudit speles un testet Interneta azartspД“Дјu vietne LatvijДЃ savas spejas tiessaiste.
    Online kazino apstiprina plasu spelu klastu, sakot no tradicionalajam galda spelem, piemeram, rulete un 21, lidz atskirigiem kaujiniekiem un pokera spelem. Katram kazino apmekletajam ir iespeja, lai izveletos pasa iecienito speli un bauditu saspringtu atmosferu, kas saistita ar spelem ar naudu. Ir ari daudzas kazino speles pieejamas atskirigas deribu iespejas, kas dod iespeju pielagoties saviem speles priekslikumiem un drosibas limenim.
    Viena no briniskigajam lietam par online kazino ir ta piedavatie pabalsti un kampanas. Lielaka dala online kazino nodrosina speletajiem atskirigus bonusus, piemeram, iemaksas bonusus vai bezmaksas griezienus. Sie bonusi

  5. Due to the high cost of the operating system and office utilities, licensed software is not available to everyone kms office – and modern security systems can be very difficult to circumvent.

  6. Наши прогнозы 1xbet сводятся к тому 1xbet зеркало – что матч будет увлекательным, так как чрезвычайно трудно дать тут безоговорочное преимущество одному из оппонентов.

  7. Uusi pelisivusto on juuri saapunut pelimarkkinoille tarjoten vauhdikkaita pelikokemuksia ja runsaasti huvia kayttajille https://axia.fi . Tama varma ja turvallinen kasinopelipaikka on suunniteltu erityisesti suomalaisille gamblerille, tarjoten suomenkielisen kayttoliittyman ja asiakastuen. Online-kasinolla on laaja valikoima peleja, kuten kolikkopeleja, poytapeleja ja live-kasinopeleja, jotka toimivat moitteettomasti saumattomasti kannettavilla laitteilla. Lisaksi kasino saaatavilla vetavia talletusbonuksia ja diileja, kuten ensitalletusbonuksen, ilmaisia pyoraytyksia ja talletus bonuksia. Pelaajat voivat odottaa nopeita kotiutuksia ja sujuvaa varojen siirtoa eri maksuvalineilla. Uusi pelisivusto tarjoaa uniikin pelikokemuksen ja on taydellinen valinta niille, jotka etsivat uusia ja mielenkiintoisia pelaamisen mahdollisuuksia.

  8. Uusi digitaalinen kasino on juuri saapunut pelaamisen maailmaan tarjoamalla jannittavia pelaamisen elamyksia ja vihellyksen huvia kayttajille https://superkasinot.fi . Tama varma ja turvallinen peliportaali on luotu erityisesti suomenkielisille pelaajille, saaatavilla suomeksi olevan kayttokokemuksen ja asiakaspalvelun. Online-kasinolla on runsaasti peliautomaatteja, kuten kolikkopeleja, korttipeleja ja livena pelattavia peleja, jotka toimivat moitteettomasti saumattomasti alypuhelimilla. Lisaksi kasino tarjoaa houkuttelevia etuja ja diileja, kuten tervetuliaisbonuksen, kierroksia ilmaiseksi ja talletusbonuksia. Pelaajat voivat odottaa pikaisia kotiutuksia ja sujuvaa varojen siirtoa eri maksutavoilla. Uusi online-kasino tarjoaa poikkeuksellisen pelikokemuksen ja on loistava vaihtoehto niille, jotka etsivat uudenaikaisia ja mielenkiintoisia pelimahdollisuuksia.

  9. Uusi nettikasino on juuri saapunut pelialalle tarjoten jannittavia pelaajakokemuksia ja runsaasti viihdetta kayttajille https://superkasinot.fi . Tama reliable ja turvallinen kasinopelipaikka on luotu erityisesti suomenkielisille kayttajille, tarjoten suomenkielisen kayttokokemuksen ja asiakastuen. Online-kasinolla on runsaasti peleja, kuten slotteja, korttipeleja ja live-kasinopeleja, jotka toimivat moitteettomasti sujuvasti mobiililaitteilla. Lisaksi kasino tarjoaa koukuttavia palkkioita ja tarjouksia, kuten liittymisbonuksen, ilmaiskierroksia ja talletus bonuksia. Pelaajat voivat odottaa valittomia kotiutuksia ja helppoa rahansiirtoa eri maksuvalineilla. Uusi pelisivusto tarjoaa uniikin pelaamisen kokemuksen ja on loistava vaihtoehto niille, jotka etsivat uudenaikaisia ja mielenkiintoisia pelivaihtoehtoja.

  10. I’m gone to inform my little brother, that he should also pay a visit this website on regular basis to obtain updated from newest news.

  11. The MGM Rewards Slot Series Finale tournament will take place on January 26 & 27, 2024. Once a specific casino has been determined to currently be the best of any available, choosing slot machines becomes the next step towards making a profit at slots. Hello i always max bet on slots and wonder if anyone believes the myth that if you bet lower you go to more bonuses. Are the slots really set up that way Slots are always a popular option for online gamers, but penny slots often take the cake as the top choice due to the low betting range. NetEnt’s Guns ‘n’ Roses is a high-flying, hard-rocking 5-reel, 25-pay line video slot full of classic rock show animations, juicy bonuses, and a 96.98% RTP, making it one of the best paying slots on BetMGM. Considering it’s a medium-volatility slot too, Guns ‘n’ Roses is capable of spitting out huge wins and a lengthy gaming experience.
    http://tmarket.gomt.co.kr/bbs/board.php?bo_table=free&wr_id=353240
    This game is another hold’em poker variation for real gamblers. Developers of the Poker … Because there is no live internet connection needed to play a good game of Texas hold’em poker, you can just play Governor of Poker 2 offline anywhere you want! o 19 cities and 27 poker locations to play What do you think about Governor of Poker 2 – OFFLINE? Do you recommend it? Why? AI shoves with the knowledge a pair is coming. The AI almost never folds and somehow chops the pot with a pair when you have a straight. Since I started playing this game, I’ve been dealt one pocket pair. And it was threes. AI goes all in pre flop with a 7 and a 2 and hits a full house. Find a different offline poker. This one forces you to either stay stagnant and win little pots here and there or pay money to try to advance. Great idea that had tons of potential, poorly executed.

  12. Playing plumber games online https://telegra.ph/Play-Plumbers-Online-Connect-Pipes-and-Solve-Puzzle-Challenges-05-13 offers an entertaining and intellectually stimulating experience. Whether you’re seeking a casual puzzle-solving adventure or a challenging brain teaser, these games provide hours of fun and excitement. So, get ready to connect pipes, overcome obstacles, and showcase your skills in the captivating world of online plumbers. Embark on a virtual plumbing journey today and immerse yourself in the thrilling puzzles that await!

  13. Компания ВолгаСталь предлагает качественное строительство любых видов заборов и ограждений в Самаре и по всей Самарской области – многолетний опыт монтажа металлоконструкций позволяет быстро и качественно монтировать заборы под ключ https://волгасталь63.рф/?p=3&cat=16 а наличие собственного производства – гарантировать разумные цены.

  14. Давайте поговорим о казино Пин Ап, которое является одним из самых популярных онлайн-казино на сегодняшний день. У этого игорного заведения есть несколько важных особенностей, которые стоит отметить.
    pin up казино
    Во-первых, казино Пин Ап всегда радует своих игроков новыми игровыми автоматами. Здесь вы найдете такие новинки, как Funky Time, Mayan Stackways и Lamp Of Infinity. Эти автоматы не только предлагают захватывающий геймплей и увлекательные сюжеты, но и дают вам возможность выиграть крупные призы. Казино Пин Ап всегда следит за последними тенденциями в игровой индустрии и обновляет свою коллекцию, чтобы удовлетворить потребности своих игроков.

  15. Way cool! Some extremely valid points! I appreciate you penning this write-up plus
    the rest of the website is also very good.

  16. After checking out a few of the blog posts on your blog, I really like your way of writing a blog.
    I book-marked it to my bookmark site list and will be checking back soon. Please
    check out my website as well and let me know how you feel.

  17. Cat Casino лучший сайт для игры. Играй в кэт на официальном сайте и зарабатывай деньги. Быстрый вывод и большие бонусы для каждого игрока. – cat вход

  18. I was just looking for this info for a while. After 6 hours of continuous Googleing, at last I got it in your web site. I wonder what’s the lack of Google strategy that do not rank this type of informative sites in top of the list. Usually the top websites are full of garbage.