是否可以在不使用 typedef 的情况下将预先声明的函数的类型用作函数指针?
函数声明:
int myfunc(float);
通过某种语法使用函数声明作为函数指针
myfunc* ptrWithSameTypeAsMyFunc = 0;
是否可以在不使用 typedef 的情况下将预先声明的函数的类型用作函数指针?
函数声明:
int myfunc(float);
通过某种语法使用函数声明作为函数指针
myfunc* ptrWithSameTypeAsMyFunc = 0;
不符合 2003 年标准。是的,随着即将到来的 C++0x 标准和 MSVC 2010 和 g++ 4.5:
decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
是的,可以在没有 typedef 的情况下声明函数指针,但不能使用函数名来做到这一点。
通常使用 typedef 是因为声明函数指针的语法有点巴洛克式。但是,不需要 typedef。你可以写:
int (*ptr)(float);
声明ptr
为一个函数指针,指向一个函数的接收float
和返回int
——不涉及 typedef。但同样,没有任何语法允许您使用该名称myfunc
来执行此操作。
是否可以在不使用 typedef 的情况下将预先声明的函数的类型用作函数指针?
我要骗一点
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.
不,不是目前。C++0x 将更改 的含义auto
,并添加一个新关键字decltype
,让您可以执行此类操作。如果您使用的是 gcc/g++,您可能还会考虑使用它的typeof
运算符,这非常相似(在处理引用时有细微的差别)。
不,没有 C++0x decltype
:
int myfunc(float)
{
return 0;
}
int main ()
{
decltype (myfunc) * ptr = myfunc;
}
gcctypeof
作为 C 的扩展(不了解 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;
有关基础知识的更多信息,请参见此处。