gpt4 book ai didi

c++ - 类模板出现在类成员访问表达式中

转载 作者:太空狗 更新时间:2023-10-29 23:03:51 25 4
gpt4 key购买 nike

引自 3.4.5/1(文档版本 N3797):

In a class member access expression (5.2.5), if the . or -> token is immediately followed by an identifier followed by a <, the identifier must be looked up to determine whether the < is the beginning of a template argument list (14.2) or a less-than operator. The identifier is first looked up in the class of the object expression. If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template.

#include <iostream>
#include <stdio.h>

struct A { };

template <typename T> class B{ };


int main(){ A *a = new A(); a->B<int>; }

查找B<int>在整个后缀表达式的上下文中是成功的。但是 clang++ 返回一个错误:

test.cpp:14:32: error: no member named 'B' in 'A'

请解释该诊断消息。

我不清楚以下内容:如果未找到标识符,clang++ 将返回错误。但是标准说If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template .

在对象表达式类作用域中找不到标识符后查找有什么意义?

最佳答案

您的构造被 §5.2.5[expr.ref]/p2 禁止,解决类成员访问表达式:

In either case, the id-expression shall name a member of the class or of one of its base classes.


If the identifier is not found, it is then looked up in the context of the entire postfix-expression and shall name a class template.

我相信此查找规则用于查找作为模板的基类。 “在对象表达式的类中”查找会找到类成员,但不会找到基类本身。 这似乎不正确,因为基类名称也被注入(inject)到派生类中(参见示例在 §11.1 [class.access.spec]/p5).


编辑:好吧,这里有一个非常人为的例子,它似乎依赖于这个规则:

#include<iostream>
using namespace std;

template <class T>
class A {
public:
void foo() { cout << "A::foo()" << endl; }
};

template <class E>
using base = A<E>;

int main() {
A<int>* bp = new A<int>();
bp->base<int>::foo();
}

正在查找 baseA找不到它,因此您还需要在表达式的上下文中查找以确定是否 <小于或开始模板参数列表。然而,这个子句有相当长的历史(早于模板别名)所以必须有另一个我遗漏的用例......

关于c++ - 类模板出现在类成员访问表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24358606/

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