0

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"

2 Answers 2

4

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; });
Sign up to request clarification or add additional context in comments.

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.