Michael Blake
Michael Blake

Reputation: 995

When passing a function as a pointer, how do I specify the parameters?

I've found a ton of info on function pointers, but one thing is really confusing. How am I supposed to specify the parameters of the function that's being passed? An example from what I've been trying to do...

void BatchDelete(string head, string filename, void (*f)(string, string));
void DeleteOneNode(string head, string song);
BatchDelete(head, filename, DeleteOneNode)

From what I've read and seen, when passing a function, it should never have parenthesis because that's a function call, but how do I specify what two strings DeleteOneNode get?

Upvotes: 0

Views: 49

Answers (1)

kfsone
kfsone

Reputation: 24249

You don't. A function pointer is a pointer to a function to be called, it is up to the call site to supply parameters.

#include <iostream>

void target(const std::string& str)
{
    std::cout << "fn " << str << "\n";
}

void caller(void (*fn)(const std::string&))
{
    fn("hello world");
}

int main()
{
    caller(target);
}

Live demo: http://ideone.com/AWsxk5

In the samples you gave, BatchDelete takes some parameters from which it appears to find songs, then it calls your callback function with the parameters needed, passes them for you - you don't need to worry about trying to pass them.

That's the point of the function pointer there, it finds the files to delete but then it wants you to provide the function do to the deleting, and more to the point, the purpose of a function pointer is a contract about receipt of the arguments from the intermediate function.

--- Edit ---

A more "batchdelete" like version of the example:

#include <iostream>

void callbackfn(std::string path, std::string filename)
{
    std::cout << "delete " << path << "\\" << filename << "\n";
}

void BatchDelete(std::string path, std::string file, void (*fn)(std::string, std::string))
{
    // pretend these are songs we found in playlist.mpl
    fn(path, "Alanis\\*.*");
    fn(path, "Mix Tape\\ReallySadSong.mp3");
}

int main()
{
    BatchDelete("C:\\Music\\", "playlist.mpl", callbackfn);
}

http://ideone.com/NEpXeC

Upvotes: 4

Related Questions