Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass member function pointer to std::function

How can I pass member function pointer to std::function through a function. I am going to explain it by comparison (Live Test):

template<class R, class... FArgs, class... Args>
    void easy_bind(std::function<R(FArgs...)> f, Args&&... args){ 
}

int main() {
    fx::easy_bind(&Class::test_function, new Class);
    return 0;
}

I get an error message:

no matching function for call to ‘easy_bind(void (Class::*)(int, float, std::string), Class*)’

I just don't understand why a function pointer cannot be passed to std::function when its being passed through a function parameter. How can I pass that function? I am willing to change the easy_bind function parameter from std::function into a function pointer but I really don't know how.

EDIT: Question simplified.

EDIT: Thanks to @remyabel, I was able to get what I needed: http://ideone.com/FtkVBg

template <typename R, typename T, typename... FArgs, typename... Args>
auto easy_bind(R (T::*mf)(FArgs...), Args&&... args)
-> decltype(fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...)) {
    return fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...);
}
like image 738
Gasim Avatar asked Jan 22 '14 00:01

Gasim


1 Answers

http://en.cppreference.com/w/cpp/utility/functional/mem_fn is what you are supposed to use

struct Mem
{
    void MemFn() {}
};

std::function<void(Mem*)> m = std::mem_fn(&Mem::MemFn);
like image 63
ACB Avatar answered Nov 15 '22 12:11

ACB