gpt4 book ai didi

c++ - 跨翻译单元不一致的模板特化状态?

转载 作者:行者123 更新时间:2023-12-04 15:52:28 25 4
gpt4 key购买 nike

请考虑以下程序:

文件 A.H

template <typename T> struct C { static constexpr int x = 42; };

文件 B.H
#include "A.H"

template <> struct C<int> { static constexpr int x = 43; };

文件 A.CC
#include "A.H"

void a() { std::cout << C<int>::x; }

文件 B.CC
#include "B.H"

void b() { std::cout << C<int>::x; }

文件主.CC
void a(); void b();

int main() { a(); b(); }

这个程序的状态如何?它是格式错误的,格式错误的,不需要诊断,是否表现出未定义的行为,或者以上都没有(没关系)?

如果以上都不是,程序的输出是什么?

如果是上述之一,它违反了什么规则?

(此外,如果 B.H 包含部分特化而不是显式特化,答案会有所不同吗?)

最佳答案

这是 [temp.arg.template]/2 :

If a specialization is not visible at the point of instantiation, and it would have been selected had it been visible, the program is ill-formed, no diagnostic required.



专攻 C<int>a() 的定义中不可见,但如果是的话就会被选中。

但更重要的是,这是 the limerick (我的间距):

When writing a specialization,
be careful about its location;
or to make it compile
will be such a trial
as to kindle its self-immolation.

关于c++ - 跨翻译单元不一致的模板特化状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60767124/

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