问题
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?
回答1:
You're right in many ways. F
is a function type, and FPT
is 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:
FPT f1 = &foo;
F * f2 = &foo;
F & f3 = foo;
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:
double callme(F & f, double val) // not: "F *" or "FPT"
{
return f(val);
// "&f" and "std::decay<F>::type" still make sense
}
回答2:
In parameter lists, function types decay to the appropriate function pointer type, such that a function of the same type can be passed as in an argument list, itself decaying to the same pointer type.
This works the same for arrays; void foo(int arg[4])
has actual first argument type int *
.
8.3.5 Functions [dcl.fct]
5 - [...] After determining the type of each parameter, any parameter of type "array of
T
" or "function returningT
" is adjusted to be "pointer toT
" or "pointer to function returningT
," respectively. [...]
The use of a function type in a declaration is covered in the same section:
10 - A typedef of function type may be used to declare a function but shall not be used to define a function.
来源:https://stackoverflow.com/questions/13258665/function-pointer-typedef