2

I know void(*)(int) is a function pointer. But I'm really confused of void(int). First, they're different types

using A = void(int);
using B = void(*)(int);
is_same<A*, B>::value == true

I can initialize a variable of type B using a function pointer but not A

void func(int x){
    cout<<x<<endl;
}
B b { func }; //ok
A a { func }; //error
A* ap { func }; //ok

But if used as function parameter types, they seem to be exchangable

void callA(A a, int arg){ a(arg); }
void callB(B b, int arg){ b(arg); }
callA(func, 1); //ok
callB(func, 1); //ok

So what is void(int) indeed? When should I use void(int) and when should I use void(*)(int)?

Stan
  • 2,010
  • 3
  • 16
  • 12

1 Answers1

3

Your A is a function type, whereas your B is a pointer-to-function type.

You have correctly identified that these are different types, but when you use A as a parameter, it's silently translated into B (for "convenience"):

[C++14: 8.3.5/5]: [..] After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively. [..]

So, in that context, it arguably doesn't matter which you use.

Otherwise, you might use A in a template parameter expecting an actual function type, e.g. std::function<void()>; you would use B to declare a bog-standard function pointer. That's a bit like how you might use a std::vector<int>, or a int* instead.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055