Reputation: 2019
I have a function which receives an object instance and a function pointer. How can I execute my function pointer on my object instance?
I have tried:
void Myclass::my_fn(Object obj, bool (*fn)(std::string str))
{
obj.fn("test"); // and (obj.fn("test"))
}
But nothing works. It tells me "unused parameters my_fn and fn"
Upvotes: 0
Views: 78
Reputation: 409482
It's because fn
is not a member function pointer of Object
. For that you have to do e.g.
bool (Object::*fn)(std::string)
Then to call it you have to do
(obj.*fn)(...);
However, if your compiler and library can support C++11, I suggest you to use std::function
and std::bind
:
void MyclasS::my_fn(std::function<bool(std::string)> fn)
{
fn("string");
}
Then call the my_fn
function as
using namespace std::placeholders; // For `_1` below
Object obj;
myclassobject.my_fn(std::bind(&Object::aFunction, &obj, _1));
With std::function
you can also use other function pointers or lambdas:
myclassobject.my_fn([](std::string s){ std::cout << s << '\n'; return true; });
Upvotes: 4
Reputation: 2031
Function pointers are something completely different form member function pointers (pointers to methods).
In case of function pointers, you don't need any object to call them:
void Myclass::my_fn(bool (*fn)(std::string str))
{
fn("test");
}
In case of member function pointers correct syntax would be:
void Myclass::my_fn(Object obj, bool (Object::*fn)(std::string str))
{
obj.*fn("test");
}
Upvotes: 0