vendredi 22 janvier 2021

std::bind member function within struct

I have a function bar that is widely applicable, and not a member of any struct. bar takes a functional/function pointer and some other arguments.

I also have many structs. They are heterogeneous in member variables.

Within each struct Foo, I want a member function of Foo to call on bar such that the functional supplied to bar is another non-static member function of Foo.

The many posts on SO related to std::bind with member functions but they seem slightly different.

#include <functional>
using namespace std;

typedef  vector<int>  V;

V bar(function<int(V)> f , V a) {
  // do work.
}

struct Foo
{
    V x;

    int f1(V y , int z) {
       // do work that involves member variable x,
       // and inputs y, z.
    }

    int f2() {
        std::function<V(int)> wrapper = std::bind(f1 , _1 , 7);
        V a;
        V c = bar(wrapper , a);
        return accumulate(c.begin(),c.end(),0);
    }
};

The error is of course:

: error: invalid use of non-static member function

Aucun commentaire:

Enregistrer un commentaire