Function pointer without typedef

Is it possible to use the type of a previously declared function as a function pointer without using typedef?

Function declaration:

int myfunc(float); 

use function declaration with some syntax as function pointer

 myfunc* ptrWithSameTypeAsMyFunc = 0; 
+7
c ++ c typedef syntactic-sugar function-pointers
source share
7 answers

Does not comply with the 2003 standard. Yes, with the upcoming C ++ 0x standard and MSVC 2010 and g ++ 4.5:

 decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0; 
+21
source share

Yes, you can declare a pointer to a function without a typedef, but there is no way to use the function name for this.

Typeed is commonly used because the syntax for declaring a function pointer is a little baroque. However, typedef is not required. You can write:

 int (*ptr)(float); 

declare ptr as a function of a pointer to a function that takes a float and returns an int - no typedef. But then again, there is no syntax that allows you to use the name myfunc for this.

+6
source share

Is it possible to use the type of a previously declared function as a function pointer without using typedef?

I'm going to cheat a little

 template<typename T> void f(T *f) { T* ptrWithSameTypeAsMyFunc = 0; } f(&myfunc); 

Of course, this is not completely error-free: it uses a function, so it needs to be defined, while things like decltype do not use this function and do not require a function definition.

+3
source share

Not now. C ++ 0x will change the value of auto and add a new decltype keyword that will allow you to do such things. If you use gcc / g ++, you can also examine its typeof operator, which is very similar (it has a slight difference when working with links).

+1
source share

No, not without C ++ 0x decltype :

 int myfunc(float) { return 0; } int main () { decltype (myfunc) * ptr = myfunc; } 
+1
source share

gcc has typeof as an extension for C (I don’t know about C ++) ( http://gcc.gnu.org/onlinedocs/gcc/Typeof.html ).

 int myfunc(float); int main(void) { typeof(myfunc) *ptrWithSameTypeAsMyFunc; ptrWithSameTypeAsMyFunc = NULL; return 0; } 
+1
source share
 int (*ptrWithSameTypeAsMyFunc)(float) = 0; 

Learn more about the basic principles here .

0
source share

All Articles