samedi 6 janvier 2018

Call a member method over a collection

I want to know if something like that it's possible in C++11. The idea here is to have a class keeping reference to a collection and provide a generic method to perform some operations over it. With the following code I have problems to call a method of the class of each item in the collection using bind:

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>

using namespace std;

class Foo {
public:
    void print() {
        cout << "hello" << endl;
    }
};

class Helper {
private:
    vector<Foo> v;
public:
    Helper() :
            v(5) {
    }
    void perform(std::function<void(Foo&)>&& f) {
        for_each(v.begin(), v.end(), f);
    }
};

int main() {
    Helper r;
    r.perform(bind(&Foo::print));
    r.perform([](Foo& f) {f.print();});
}

I guess bind wants a real instance of Foo. I'm wondering if it's possible to use bind instead of lambda. I'm asking just because I want to understand how C++11 works. Is it needed bind with mem_fn?

Aucun commentaire:

Enregistrer un commentaire