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()
{
func(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)
are two completely different stuff.
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())
]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With