Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c++ - 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

question from:https://stackoverflow.com/questions/65850642/stdbind-member-function-within-struct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first (hidden) argument of a argument of a member function is the this variable. So the correct way to use std::bind here is

std::function<int(int)> wrapper = std::bind(&Foo::f1, this, _1 , 7);

However, modern C++, the correct way to do this is to use a lambda. I usually use explicit binds for this, so:

auto wrapper = [this](V v) {
  return f1(v, 7);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...