Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Binder2nd objects that store pointers to member functions be used in a map?

Tags:

c++

stl

My question is similar to this one. I need to store pointers to member functions in the map. The member functions takes an argument, which has to binded by a specific value while constructing the map. How do i do that? Should map have a binder2nd object as its value.

Eg:

enum { FOO, BAR };

exMap["foo"]  = bind2nd(&classA::Func, FOO);

I don't know how to declare this map.

like image 827
excray Avatar asked Nov 28 '25 21:11

excray


1 Answers

Here is an example that works using Boost.Function:

#include "boost/function.hpp"
#include <map>
#include <iostream>
#include <functional>

struct Foo {
    void bar(int x) {
        std::cout << "bar called with x=" << x << std::endl;
    }
};

int main()
{
    Foo foo;
    std::map<int, boost::function<void (Foo*)> > m;

    m[1] = std::bind2nd(std::mem_fun(&Foo::bar), 3);

    m[1](&foo);

    return 0;
}

Apparently this is not possible with binder2nd, because it is not default-constructible, which is a requirement for the values of an std::map.

Since you cannot use Boost, you will have to write your own binder.

like image 124
Björn Pollex Avatar answered Dec 01 '25 10:12

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!