Sirop4ik
Sirop4ik

Reputation: 5233

How to pass method(as callback) as param to method?

I have static method in my Utils class

This is definition

/*static*/ void Utils::copy_files(void(*progress_callback)(int, int),
        std::string const & path_from,
        std::string const & path_to)
    {
      ....
    }

And here using

void TV_DepthCamAgent::progress_callback(int count, int copied_file)
{
    printf("Progress :: %d :: %d\n", count, copied_file);
}

void TV_DepthCamAgent::foo()
{
    ...
    shared::Utils::copy_files(progress_callback, path_from_copy, path_to_copy);
    ...
}

And this is an errors that I get

E0167 argument of type "void (TV_DepthCamAgent::)(int count, int copied_file)" is incompatible with parameter of type "void ()(int, int)"

Error C3867 'TV_DepthCamAgent::progress_callback': non-standard syntax; use '&' to create a pointer to member

What am I doing wrong?

Upvotes: 0

Views: 81

Answers (1)

Object object
Object object

Reputation: 2054

Since you've tagged this C++ i'm assuming you want a C++ solution.

Since C++11 we can use std::function instead of the awkward C style pointer-to-function syntax.

So void(*progress_callback)(int, int) becomes std::function<void(int, int)> progress_callback

In regards to why you get that error it is because to pass a function pointer you must pass the function by reference

...
    shared::Utils::copy_files(&progress_callback);
...

You must then pass the required arguments when you call it in copy_files.

You should use std::function and std::bind for this instead of the C style you seem to be writing in

Upvotes: 3

Related Questions