a strange use of typedef
I have never see a grammar in c++ like this before:
typedef int (callback)(int);
what really does this really mean?I just find that if I create a statement
callback a;
It's effect is very very similar to a forward function declaration.
below is the code I had written
#include<cstdio>
int callbackfunc(int i)
{
printf("%d\n",i);
return i*i;
}
// you can also use typedef int (callback)(int) here!
typedef int (*callback)(int);
void func(callback hook)
{
hook(hook(3));
}
int main()
{
f开发者_如何学Pythonunc(callbackfunc);
getchar();
return 0;
}
You can use
typedef int (*callback)(int);//this is very common to use
in this code,but if we change it to
typedef int (callback)(int); //I'm puzzled by this !
this will also get the same result!
and I know typedef int (*callback)(int)
and typedef int (callback)(int)
Its because of the fact that in the parameter declaration, the function-type is adjusted to become a pointer-to-function-type.
typedef int type(int);
typedef int (*type)(int);
The first typedef defines a type which is called function-type
, while the second typedef defines a type which is called pointer-to-function-type
. In the parameter declaration, function-type is adjusted to become a pointer to function type.
§13.1/3 (C++03) says,
Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).
[Example:
void h(int());
void h(int (*)()); // redeclaration of h(int())
void h(int x()) { } // definition of h(int())
void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]
An interesting example of the exclusive usage of function-type
Suppose you've a typedef, defined as:
typedef void funtype();
then you can use this to define member-function as:
struct A
{
//member function declaration.
funtype f; //equivalent to : void f();
};
void A::f() //definition
{
std::cout << "haha" << std::endl;
}
Test code:
int main() {
A a;
a.f(); //call member function
}
Output:
haha
Online demo: http://ideone.com/hhkeK
It's because a function implicitly becomes a function pointer where necessary. These are identical:
func(callbackfunc);
func(&callbackfunc);
精彩评论