.cpp 文件中的模板专业化 + .h 文件中的主模板声明
根据 https://eel.is/c++draft/temp.expl .spec#7:
如果模板、成员模板或类模板的成员是显式特化的,则该特化的声明应可从该特化的每次使用中访问,这将导致在每个翻译单元中发生隐式实例化。发生这种使用的情况;无需诊断。
因此我想知道,以下程序是否格式错误,NDR?
// foo.h
template <typename T>
void foo();
// Specialization not declared in the header!
// foo.cpp
#include "foo.h"
template <>
void foo<int>()
{
// ...
}
// main.cpp
#include "foo.h"
int main()
{
foo<int>();
}
According to https://eel.is/c++draft/temp.expl.spec#7:
If a template, a member template or a member of a class template is explicitly specialized, a declaration of that specialization shall be reachable from every use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
Therefore I wonder, is the following program ill-formed, NDR?
// foo.h
template <typename T>
void foo();
// Specialization not declared in the header!
// foo.cpp
#include "foo.h"
template <>
void foo<int>()
{
// ...
}
// main.cpp
#include "foo.h"
int main()
{
foo<int>();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来这个确切的案例包含在标准委员会的“已关闭问题列表”中,您可以阅读
长话短说:
请注意,您可以找到很多与此非常相似的问题。例如,我发现这个,其中一位回答者引用了工作组讨论。
Looks like this exact case is covered in the standards committee's "Closed Issues List", which you can read here, very hard to get more authoritative than that.
TL;DR:
Note that you can find quite a few SO questions that are pretty similar to this. I found this one for example, in which one answerer cites the working group discussion.
这是。经过所有预处理后,这是
main.cpp
:您可能会收到类似链接器错误:
undefined reference to 'void foo()'
。您可能不会收到错误(预编译头、动态库...)
为什么不需要诊断?
第4阶段:预处理(上面的代码是在这个阶段形成的)
第 7 阶段:编译(生成翻译单元)
第 8 阶段:模板实例化发生
第九阶段:最后一个阶段。这是找到(或未找到)函数定义并将其链接到可执行文件的时间
请参阅:翻译阶段
It is. This is
main.cpp
after all the pre-processing:You might get a linker error like:
undefined reference to 'void foo<int>()'
.You might not get an error (pre-compiled header, dynamic library...)
Why is diagnosing not required?
Phase 4: Preprocessing (the code above is formed during this phase)
Phase 7: Compilation (producing translation units)
Phase 8: Template instantiation occurs
Phase 9: The last one. This is when the function definition is found (or not) and linked to the executable
See: Translation Phases