function pointer typedef

纵饮孤独 提交于 2019-12-12 04:35:58

问题


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 returning T" is adjusted to be "pointer to T" or "pointer to function returning T," 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!