不带 typedef 的函数指针
是否可以在不使用 typedef 的情况下使用预先声明的函数的类型作为函数指针?
函数声明:
int myfunc(float);
通过某种语法将函数声明用作函数指针
myfunc* ptrWithSameTypeAsMyFunc = 0;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不符合 2003 年标准。是的,随着即将推出的 C++0x 标准以及 MSVC 2010 和 g++ 4.5:
Not as per the 2003 standard. Yes, with the upcoming C++0x standard and MSVC 2010 and g++ 4.5:
是的,可以在没有 typedef 的情况下声明函数指针,但不可能使用函数名称来执行此操作。
通常使用 typedef,因为声明函数指针的语法有点巴洛克式。但是,typedef 不是必需的。您可以这样写:
将
ptr
声明为函数指针,指向采用float
并返回int
的函数——不涉及 typedef。但同样,没有任何语法允许您使用名称myfunc
来执行此操作。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:
to declare
ptr
as a function pointer to a function takingfloat
and returningint
-- no typedef is involved. But again, there is no syntax that will allow you to use the namemyfunc
to do this.当然,这并不是完全没有陷阱
:它使用了函数,因此必须定义它,而诸如 decltype 之类的东西不使用函数并且不需要要定义的函数。
I'm going to cheat a bit
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
运算符,它非常相似(在处理引用时有细微的差别)。No, not at the present time. C++0x will change the meaning of
auto
, and add a new keyworddecltype
that lets you do things like this. If you're using gcc/g++, you might also look into using itstypeof
operator, which is quite similar (has a subtle difference when dealing with references).不,没有 C++0x
decltype
就不行:No, not without C++0x
decltype
:gcc 有
typeof
作为 C 的扩展(不了解 C++)( http://gcc.gnu.org/onlinedocs/gcc/Typeof.html )。gcc has
typeof
as an extension for C (don't know about C++) ( http://gcc.gnu.org/onlinedocs/gcc/Typeof.html ).有关基础知识的更多信息,请参阅此处。
See here for more info on the basics.