8

是否可以在不使用 typedef 的情况下将预先声明的函数的类型用作函数指针?

函数声明:

int myfunc(float);

通过某种语法使用函数声明作为函数指针

myfunc* ptrWithSameTypeAsMyFunc = 0;
4

7 回答 7

23

不符合 2003 年标准。是的,随着即将到来的 C++0x 标准和 MSVC 2010 和 g++ 4.5:

decltype(myfunc)* ptrWithSameTypeAsMyFunc = 0;
于 2010-09-22T14:54:18.067 回答
7

是的,可以在没有 typedef 的情况下声明函数指针,但不能使用函数名来做到这一点。

通常使用 typedef 是因为声明函数指针的语法有点巴洛克式。但是,不需要 typedef。你可以写:

int (*ptr)(float); 

声明ptr为一个函数指针,指向一个函数的接收float和返回int——不涉及 typedef。但同样,没有任何语法允许您使用该名称myfunc来执行此操作。

于 2010-09-22T14:54:21.543 回答
3

是否可以在不使用 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.

于 2010-09-22T18:34:03.067 回答
1

不,不是目前。C++0x 将更改 的含义auto,并添加一个新关键字decltype,让您可以执行此类操作。如果您使用的是 gcc/g++,您可能还会考虑使用它的typeof运算符,这非常相似(在处理引用时有细微的差别)。

于 2010-09-22T14:56:19.687 回答
1

不,没有 C++0x decltype

int myfunc(float)
{
  return 0;
}

int main ()
{
  decltype (myfunc) * ptr = myfunc;
}
于 2010-09-22T14:58:24.913 回答
1

gcctypeof作为 C 的扩展(不了解 C++)(http://gcc.gnu.org/onlinedocs/gcc/Typeof.html)。

int myfunc(float);

int main(void) {
    typeof(myfunc) *ptrWithSameTypeAsMyFunc;
    ptrWithSameTypeAsMyFunc = NULL;
    return 0;
}
于 2010-09-22T15:03:13.803 回答
0
int (*ptrWithSameTypeAsMyFunc)(float) = 0;  

有关基础知识的更多信息,请参见此处

于 2010-09-22T14:55:36.080 回答