1

I'm trying to make a class method that takes a function pointer (regular C function pointer, not a class method pointer) as a parameter. The only thing that comes up when I search is how to create/use a member function pointer, which I'm NOT trying to do. So here's a method that takes a function pointer that returns a bool and takes two ints as parameters:

class ExampleA
{
public:
  void sort(WHAT_GOES_HERE); // Should it be the same as method definition below?
};

ExampleA::sort(bool (*customSort)(int, int)) // Hopefully this is correct
{
  // Use function pointer
}

Is there a way to declare the parameter in the method declaration without naming it like a method with an int parameter?

class ExampleB
{
public:
  void someFunction(int); // Not named here
};

ExampleB::someFunction(int varName)
{
  // do whatever
}
10101
  • 320
  • 2
  • 7
  • ###See also [How do function pointers in C work?](http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Wheeler Sep 12 '14 at 04:47

3 Answers3

2

Yep! Just leave out the name.

void sort(bool (*)(int, int));
nneonneo
  • 171,345
  • 36
  • 312
  • 383
2
bool (*)(int, int)

Basically, remove the name of the variable to get a declaration without a variable name.

However, you are often better off with a typedef:

typedef bool(*custom_sorter)(int, int);

class ExampleA {
public:
  void sort(custom_sorter);
};

ExampleA::sort(custom_sorter customSort) {
  // Use function pointer
}

which is equivalent.

As I personally hate the syntax to declare a function pointer, in C++11 I might do:

template<class T> using type=T;

...

  void sort(type<bool(int,int)>*)

which puts the signature type together, then I put a * after it to make it a pointer.

But I'm strange.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

The declaration should match the definition, so WHAT_GOES_HERE should be bool (*customSort)(int, int), and also the function definition should have the return type void specified.

You can optionally leave out the name customSort, it makes no difference.

This is somewhat inflexible; consider making it a function template that accepts a functor or a std::function instead of a function pointer; then your callers can call it with a wider range of functions.

M.M
  • 138,810
  • 21
  • 208
  • 365