c++ - typedef 的奇怪用法

标签 c++ typedef

我以前从未在 c++ 中看到过这样的语法:

typedef int (callback)(int);

这到底是什么意思?我只是发现如果我创建一个语句

  callback a;

它的效果非常类似于前向函数声明。

下面是我写的代码

#include<cstdio>

int callbackfunc(int i)
{
    printf("%d\n",i);
    return i*i;
}

// you can also use typedef int (callback)(int) here!
typedef int (*callback)(int);

void func(callback hook)
{
    hook(hook(3));
}

int main()
{
    func(callbackfunc);
    getchar();
        return 0;
}

你可以使用

typedef int (*callback)(int);//this is very common to use

在这段代码中,但是如果我们把它改成

typedef int (callback)(int); //I'm puzzled by this !

这也会得到相同的结果!

我知道 typedef int (*callback)(int)typedef int (callback)(int)
是两种完全不同的东西。

最佳答案

因为在参数声明中,function-type被调整为pointer-to-function-type.

typedef int type(int); 
typedef int (*type)(int); 

第一个 typedef 定义了一个称为 function-type 的类型,而第二个 typedef 定义了一个称为 pointer-to-function-type 的类型。在参数声明中,function-type被调整为指向函数类型的指针。

§13.1/3 (C++03) 说,

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).

[Example:
    void h(int());
    void h(int (*)()); // redeclaration of h(int())
    void h(int x()) { } // definition of h(int())
    void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]

函数类型独占用法的有趣例子

假设您有一个 typedef,定义为:

typedef void funtype();

然后您可以使用它来定义成员函数:

struct A
{
   //member function declaration. 
    funtype f; //equivalent to : void f();
};

void A::f() //definition
{
  std::cout << "haha" << std::endl;
}

测试代码:

int main() {
        A a;
        a.f(); //call member function
}

输出:

haha

在线演示:http://ideone.com/hhkeK

关于c++ - typedef 的奇怪用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557968/

相关文章:

c++ - 选择默认的 gcc/g++ 编译器

c++ - 在新线程中调用 OpenCV 函数 Canny() 会导致段错误

c# - 从托管C#代码中调用非托管C++代码以生成脱机域加入Blob

c - 为什么函数指针的 typedef 不同于常规的 typedef?

C++ - 如何在函数声明中使用模板 typedef 解决方法?

c++ - Visual Studio 在 vmware 中与 gcc/gdb 交叉编译 -> 内存访问错误

c++ - 如何在 ns3 中使用属性

c - 使用 typedef 结构时出现错误 'a value of type "X *"cannot be assigned to an entity of type "X *"'

c++ - 为什么这个构造函数重载不起作用? (发生模板和类型定义)

c - header 中 typedef 的限制,源代码中定义的结构