C ++解析器如何区分比较和模板实例化? [英] How does a parser for C++ differentiate between comparisons and template instantiations?

查看:97
本文介绍了C ++解析器如何区分比较和模板实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,符号'<'和'>'用于比较以及表示模板参数.因此,代码段

In C++, the symbols '<' and '>' are used for comparisons as well as for signifying a template argument. Thus, the code snippet

[...] Foo < Bar > [...]

可以解释为以下两种方式中的任何一种:

might be interpreted as any of the following two ways:

  • 具有模板参数Bar的Foo类型的对象
  • 将Foo与Bar进行比较,然后将结果与下一个结果进行比较

C ++编译器的解析器如何有效地在这两种可能性之间做出决定?

How does the parser for a C++ compiler efficiently decide between those two possibilities?

推荐答案

如果已知Foo是模板名称(例如,范围内是template <...> Foo ...声明,或者编译器看到了template Foo序列),则Foo < Bar不能作为比较.它必须是模板实例化的开始(或本周称为Foo < Bar >的任何东西).

If Foo is known to be a template name (e.g. a template <...> Foo ... declaration is in scope, or the compiler sees a template Foo sequence), then Foo < Bar cannot be a comparison. It must be a beginning of a template instantiation (or whatever Foo < Bar > is called this week).

如果Foo不是 模板名称,则Foo < Bar是一个比较.

If Foo is not a template name, then Foo < Bar is a comparison.

在大多数情况下,我们知道Foo是什么,因为标识符通常必须在使用前声明,因此确定一种方法或另一种方法没有问题.但是有一个例外:解析模板代码.如果Foo<Bar>在模板内部,并且Foo的含义取决于模板参数,则不知道Foo是否是模板.语言标准指示除非有关键字template否则将其视为非模板.

In most cases it is known what Foo is, because identifiers generally have to be declared before use, so there's no problem to decide one way or the other. There's one exception though: parsing template code. If Foo<Bar> is inside a template, and the meaning of Foo depends on a template parameter, then it is not known whether Foo is a template or not. The language standard directs to treat it as a non-template unless preceded by the keyword template.

解析器可以通过将上下文反馈给词法分析器来实现此目的.根据解析器提供的上下文,词法分析器将Foo识别为不同类型的令牌.

The parser might implement this by feeding context back to the lexer. The lexer recognizes Foo as different types of tokens, depending on the context provided by the parser.

这篇关于C ++解析器如何区分比较和模板实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆