对于嵌套模板,`>>` 何时成为标准 C++(而不是`> >`)?

2021-12-13 00:00:00 templates c++

我似乎记得,在过去,在处理嵌套模板参数时被警告不要将两个 > 字符放在彼此旁边(没有空格).我什至依稀记得声明了向量的向量并遇到了这个编译错误.

I seem to recall, in times of yore, being warned against putting two > characters right next to each other (without a space) when dealing with nested template parameters. I even vaguely remember declaring vectors of vectors of whatever and encountering this compilation error.

但现在我发现编译可怕的>>...

But now I find that there is absolutely nothing wrong with compiling the dreaded >>...

我的问题是:

这个约定在什么时候成为可以接受的做法?

At what point did this convention become an acceptable practice?

它是标准 C++ 的一部分吗?

Is it part of standard C++?

它是否一直是标准的一部分,而我在大学使用的编译器(以及我的教授)还不支持它?

Was it always part of the standard and the compilers I used (and the professors I had) in college just didn't support it yet?

也许这些问题有点历史,但对我来说,适当的历史背景似乎使实际记忆变得微不足道.

Maybe these questions are a tad bit historical, but for me it seems that proper historical context makes actual remembering trivial.

推荐答案

使用嵌套 >>> 关闭的模板是 正式支持 即将推出的标准 C++0x(现在是 C++11).以前,您需要空间或编译器为您加倍努力(并且做了标准未指明的事情).

Templates closed with nested >> are officially supported by the upcoming standard C++0x (now C++11). Previously you would need the space, or a compiler that went the extra mile for you (and did things not indicated by the standard).

问题源于C中的>>是右移运算符,它是一个单独的词法标记,与两个单独的>冲突code> 在经典构造的 C++ 编译器的解析阶段需要的标记(并且仅在模板的情况下,而不是在它实际上是右移时).换句话说,>>,如果允许关闭嵌套模板,在词法上是模棱两可的,但是这可以(并且正在)在解析过程中通过额外的复杂性来解决(这在现代 C++ 中实际上是没什么新鲜的).

The issue stems from the fact that >> in C is the right-shift operator, which is a single lexical token, which conflicts with the two separate > tokens that would be needed during the parsing stage in a classically-constructed C++ compiler (and only in the case of templates, not when it actually is a right-shift). In other words, the >>, if allowed to close nested templates, is lexically ambiguous, but this can be (and is being) addressed by extra sophistication during parsing (which in modern C++ is really nothing new).

相关文章