C++模板别名的理解

故事背景:

最近在看邓俊辉老师的书《数据结构(C++语言版》。不得不说这本书写的太好了,强烈推荐大家看看。

我以前也学过C++,基础的语法还是知道的,也知道C++里模板的用法。所以我满以为凭这点底子看这本书的示例代码应该是没问题的。我还特地找了一个C++在线编译器wandbox。这个在线编译器支持多种版本的C++语法,还支持多文件。

在看到第三章列表节点模板类的示例代码时,我看不懂了。代码是这样的:

typedef int Rank; //秩
#define ListNodePosi(T) ListNode<T>* //列表节点位置

template <typename T> struct ListNode { //列表节点模板类(以双向链表形式实现)
// 成员
T data; ListNodePosi(T) pred; ListNodePosi(T) succ; //数值、前驱、后继
// 极造函数
ListNode() {} //针对header和trailer的构造
ListNode( T e, ListNodePosi(T) p = NULL, ListNodePosi(T) s = NULL)
 : data(e), pred(p), succ(s) {} //默认构造器
// 操作接口
ListNodePosi(T) insertAsPred(T const& e); //紧靠当前节点之前插入新节点
ListNodePosi(T) insertAsSucc(T const& e); //紧随当前节点之后插入新节点
};

看不懂的有两句(凭什么可以这样写?为什么我写不出来?):

#define ListNodePosi(T) ListNode<T>*

ListNodePosi(T) pred;

先来看看微软msdn对#define的语法解释:

#define Directive (C/C++)

#define identifier token-stringopt
#define identifier ( identifieropt,...,identifieropt)token-stringopt

The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier. For more information, see Tokens.

define指令使得编译器把源文件每个标识符都替换成token-string。只有当标识符构成一个token的时候才会被替换。那就是,标识符出现在注释,字符串,或者是更长标识符的一部分时不会被替换。

什么是token?(这个词很常见哟,尤其是涉及到分词的时候经常用到这个词)

扫描二维码关注公众号,回复: 2345936 查看本文章

A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: identifiers, keywords, literals, operators, punctuators, and other separators. A stream of these tokens makes up a translation unit.

一个token就是C++编程中对编译器有意义的最小元素。C++解析器会识别这些token:标识符,关键字,字面量,操作符,标点符号和其它分隔符。一连串这样的token构成了一个翻译单元。

比如定义一个变量, int a; 这就是一个token。因为它是有意义的,编译器能够编译它。
字面量就是“硬编码”。比如String str = "abcd"。这个"abcd"就是一个字面量。

原文链接

猜你喜欢

转载自blog.csdn.net/weixin_40581617/article/details/81185411
今日推荐