views:

138

answers:

7

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

function declaration:

int myfunc(float);

use the function declaration by some syntax as function pointer

myfunc* ptrWithSameTypeAsMyFunc = 0;
+13  A: 

Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:

decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
Anthony Williams
@anthony looks nice - will check this...
David Feurle
@anthony the problem is my code does not compile with c++0x enabled. So this is no usable solution for me :S
David Feurle
With g++ you can use `typeof(myfunc)` instead of `decltype(myfunc)` and it works even in non-C++0x mode.
Anthony Williams
for me this solution is not usable but I will accept this as an answer. Perhaps I will change my code until it compiles with c++0x.
David Feurle
+4  A: 

Yes, it is possible to declare a function pointer without a typedef, but no it is not possible to use the name of a function to do that.

The typedef is usually used because the syntax for declaring a function pointer is a bit baroque. However, the typedef is not required. You can write:

int (*ptr)(float); 

to declare ptr as a function pointer to a function taking float and returning int -- no typedef is involved. But again, there is no syntax that will allow you to use the name myfunc to do this.

Tyler McHenry
A: 
int (*ptrWithSameTypeAsMyFunc)(float) = 0;  

See here for more info on the basics.

Steve Townsend
A: 

No, not at the present time. C++0x will change the meaning of auto, and add a new keyword decltype that lets you do things like this. If you're using gcc/g++, you might also look into using its typeof operator, which is quite similar (has a subtle difference when dealing with references).

Jerry Coffin
A: 

No, not without C++0x decltype:

int myfunc(float)
{
  return 0;
}

int main ()
{
  decltype (myfunc) * ptr = myfunc;
}
wilx
A: 

gcc has typeof as an extension for C (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;
}
pmg
GCC doesn't need the `typeof` extension in C++ because it implements the (soon to be standard) `decltype`, which serves pretty much the same purpose.
MSalters
+1  A: 

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

I'm going to cheat a bit

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

f(&myfunc);

Of course, this is not completely without pitfalls: It uses the function, so it must be defined, whereas such things as decltype do not use the function and do not require the function to be defined.

Johannes Schaub - litb