What is the difference between
typedef double F(double)
and
typdedef double (*FPT)(double);
?
It seems to me that I can pass both as arguments to a function, i.e.
bar1(FPT f);
bar2(F f);
but while I can do
FPT f = &foo;
I can not do
F f = foo;
i.e. I can not create variables of type F?
You’re right in many ways.
Fis a function type, andFPTis a function pointer type.If you have an object of function type, you can take its address and get a function pointer. However, objects of function type aren’t real, first-class C++ objects. Only actual functions are of such a type, and you can’t create an object that is a function (other than by declaring a function!) and thus you cannot assign to it (as in
F f = foo;).The only way you can refer to a function is via a function pointer or reference:
See also this answer.
Note that for a callback I would prefer the reference type over the pointer type, because it’s more natural compared to how you pass any other variable, and because you can apply address-of and decay to the reference and get the pointer, which you can’t do with a pointer: