gpt4 book ai didi

c++ - 当 `new v < new v` 不是模板时,为什么 gcc 拒绝 `v`?

转载 作者:可可西里 更新时间:2023-11-01 15:23:56 25 4
gpt4 key购买 nike

简单的测试用例:

#include <iostream>
struct v {};
int main() {
std::cout << __VERSION__ << '\n' << (new v < new v) << '\n';
}

我知道比较指针有一个未指定的结果,但这与这里无关(并且可以通过更多的击键产生类似的例子,如后面的 coliru 片段)。

我手边的 C++ 标准在 §14.2 第 3 段中说:

After name lookup finds that a name is a template-name or that an operator-function-id or a literal-operator-id refers to a set of overloaded functions any member of which is a function template, if this is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator.

因为 v 既不是模板名称也不是函数 ID,我不明白为什么这应该适用。显然,clang 也没有。 :

4.2.1 Compatible Clang 3.8.0 (tags/RELEASE_380/final 263969)
1

然而,gcc (6.3.0) 提示:

main.cpp: In function 'int main()':

main.cpp:4:46: error: 'v' is not a template
std::cout << __VERSION__ << '\n' << (new v < new v) << '\n';
^

我(和 clang)在这里遗漏了什么吗?

没有未指定行为的版本:clang gcc

带有减号运算符而不是小于号的版本:gcc (没有编译错误)


附录

Gcc 在函数方面没有同样的问题;与 template functions它坚持 < 必须是模板参数定界符,而不是 non-template functions .这增加了它是一个错误的论点的重要性,所以我将其归档为 Bug 79192 .


备注:

万一有人好奇,这是我在尝试回答 this question 时出现的,发问者正在为一种类似 C++ 的语言编写语法,并偶然发现了上述歧义。我想解释 C++ 使用的解决方案,但两个编译器之间的差异使它变得困难。

最佳答案

这是一个错误,或者至少错误报告已被 GCC 维护者接受。

在评论中,Johannes Schaub-litb 指出拒绝此构造的代码位于 cp/parser.c 的第 16781 行:

  /* There is no valid C++ program where a non-template type is
followed by a "<". That usually indicates that the user thought
that the type was a template. */
cp_parser_check_for_invalid_template_id (parser, type, none_type,
token->location);

并且注释不正确,因为检查还拒绝了其他有效程序,例如

struct A {
operator A();
};

void operator<(A (A::*)(), A);

int main() {
&A::operator A < A();
}

( on coliru )

关于c++ - 当 `new v < new v` 不是模板时,为什么 gcc 拒绝 `v`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com