function pointer without typedef
Is it posible to use the typ开发者_开发技巧e 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;
Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:
decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
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.
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.
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).
No, not without C++0x decltype
:
int myfunc(float)
{
return 0;
}
int main ()
{
decltype (myfunc) * ptr = myfunc;
}
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;
}
int (*ptrWithSameTypeAsMyFunc)(float) = 0;
See here for more info on the basics.
精彩评论