Strange use of typedef

I have never seen a grammar in C ++ like this before:

typedef int (callback)(int); 

what does it really mean? I just find that if I create an operator

  callback a; 

The effect is very similar to declaring a forward function.

below is the code i wrote

 #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 ! 

it will also give the same result!

and I know typedef int (*callback)(int) and typedef int (callback)(int)
these are two completely different materials.

+6
source share
2 answers

Due to the fact that in the parameter declaration the function type is configured to become a type of function pointer.

 typedef int type(int); typedef int (*type)(int); 

The first typedef defines a type called function-type , and the second typedef defines a type called pointer-to-function-type . In the parameter declaration, the function type is configured to become a pointer to the function type.

ยง13.1 / 3 (C ++ 03) says:

Declarations of parameters that differ only in this are a type of function, and the other is a pointer to the same type of function equivalent . That is, the type of function is configured to become a pointer to the type of function (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 use of a functional type

Suppose you have a typedef that is defined as:

 typedef void funtype(); 

then you can use this to define a 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; af(); //call member function } 

Conclusion:

 haha 

Online demo: http://ideone.com/hhkeK

+11
source

This is because a function implicitly becomes a function pointer where necessary. They are identical:

 func(callbackfunc); func(&callbackfunc); 
+3
source

Source: https://habr.com/ru/post/898086/


All Articles