gpt4 book ai didi

c++ - 为什么即使直到最后才定义实际类型,依赖名称也可以被认为是完整的

转载 作者:可可西里 更新时间:2023-11-01 16:37:57 25 4
gpt4 key购买 nike

Consider this example :

template <class T>
void Yeap(T);

int main() {
Yeap(0);
return 0;
}

template <class T>
void YeapImpl();

struct X;

template <class T>
void Yeap(T) {
YeapImpl<X>(); // pass X to another template
}

template <class T>
void YeapImpl() {
T().foo();
}

struct X {
void foo() {}
};

请注意 struct X 直到最后才定义。我曾经认为所有 odr 使用的名称在实例化时必须是完整的。但是在这里,编译器如何在定义之前将其视为完整类型?

我查看了cppreference中依赖名称和函数模板实例化的绑定(bind)规则和查找规则,但没有一个能解释这里发生的事情。

最佳答案

我认为这个程序格式错误,不需要诊断。

[temp.point]/8阅读,删除不相关的部分:

A specialization for a function template [...] may have multiple points of instantiations within a translation unit, and in addition to the points of instantiation described above, for any such specialization that has a point of instantiation within the translation unit, the end of the translation unit is also considered a point of instantiation. [...] If two different points of instantiation give a template specialization different meanings according to the one-definition rule, the program is ill-formed, no diagnostic required.

YeapImpl<X>有两个实例化点:在问题的注释行和翻译单元末尾调用它的地方。在第一个实例化点中,X是不完整的,这会使函数的主体格式错误。在第二个实例化点中,X是完整的,使 body 结构良好。

这两个专业具有 [非常] 不同的含义。

关于c++ - 为什么即使直到最后才定义实际类型,依赖名称也可以被认为是完整的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388910/

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