typedef cell (*proc_type)(const std::vector<cell> &); 有什么作用?

What does typedef cell (*proc_type)(const std::vector<cell> &); do?

本文关键字:cell lt gt 什么 作用 std proc type typedef const vector      更新时间:2023-10-16

当我看到这一行时,我正在看这篇文章。

简而言之,代码如下所示:

struct cell {
  typedef cell (*proc_type)(const std::vector<cell> &);
  typedef std::vector<cell>::const_iterator iter;
  typedef std::map<std::string, cell> map;
  cell_type type;
  std::string val;
  std::vector<cell> list;
  proc_type proc;
  environment * env;
  cell(cell_type type = Symbol) : type(type), env(0) {}
  cell(cell_type type, const std::string & val) : type(type), val(val), env(0) {}
  cell(proc_type proc) : type(Proc), proc(proc), env(0) {}
};

那么typedef单元格(*proc_type((const std::vector &(是什么? 男孩
typedef 应该像这样使用

typedef (existing) (new)

那么,当我们可以使用 cell 代替时,为什么要声明如此复杂的新类型呢?

你断言"typedef应该像typedef (existing) (new)一样使用"是完全不正确的。不,在一般情况下,它不会那样使用。只有最基本的 typedef 声明可能遵循该格式。

C(或C++(中typedef声明的语法基于普通声明的语法。事实上,它是完全相同的语法,添加了typedef关键字。在这些语言中,声明不能像您在案件中试图做的那样明确地分为两部分。声明语法要复杂得多。声明的名称通常位于描述该名称类型的令牌中间。

对于一个简单的示例,数组类型为 int [10] 的名为 a 的对象的声明如下所示

int a[10];

它有部分在名字的左边(int(和名字的右边([10](。同样,在 typedef 声明中,描述类型的标记可以(并且将(位于新类型名称的左侧和右侧。在您的示例中

typedef cell (*proc_type)(const std::vector<cell> &);

正在声明新名称proc_type,而围绕它的所有内容实际上都描述了这个新 typedef 名称将代表的类型cell (*)(const std::vector<cell> &)。它是一种指针类型:指向接收参数并返回cellconst std::vector<cell> &函数的指针。

那么typedef cell (*proc_type((const std::vector &(; 是做什么的呢?

它声明一个名为 proc_type 的新类型,该类型是指向使用编译器的默认调用约定(通常为 __cdecl(的函数的指针,将const std::vector<cell> &作为输入,并返回cell

然后,您显示的内容之外的代码会将一个函数分配给cell::proc成员,大概是为了让cell用户以后可以在需要时调用该函数,而无需知道或关心实际调用的函数(在您链接到的代码中,这些函数是通过cell(proc_type)构造函数add_globals()分配的(。

经典回调场景。

您可以通过将它们

粘贴到在线 cdecl 网站中来推断复杂的 typedef,例如函数指针:

http://cdecl.org

或者使用"左右"规则:

http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html

typedef cell (*proc_type)(const std::vector &);

proc_type定义为函数指针类型cell (*)(const std::vector&)