gpt4 book ai didi

c++ - 跨 TU 的类模板重载

转载 作者:可可西里 更新时间:2023-11-01 17:34:28 27 4
gpt4 key购买 nike

考虑以下 C++11 应用程序:

A.cpp:

template<typename T>
struct Shape {
T x;
T area() const { return x*x; }
};

int testA() {
return Shape<int>{2}.area();
}

B.cpp:

template<typename T, typename U = T>
struct Shape {
T x;
U y;
U area() const { return x*y; }
};
int testB() {
return Shape<int,short>{3,4}.area();
}

main.cpp :

int testA();
int testB();
int main() {
return testA() + testB();
}

虽然它可以编译(只要 A 和 B 在不同的 TU 中),但它看起来不正确,我很难弄清楚原因。

因此我的问题是:这是否违反了 ODR、重载或任何其他规则,如果是,the Standard 的哪些部分?违反了,为什么?

最佳答案

这是 ODR 违规。 Template names have linkage .这两个模板名称都有外部链接,如 [basic.link]/4说:

An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage. A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of

  • [...]
  • a template.

因此,由于两个模板共享一个名称,这意味着 [basic.def.odr]/5适用:

There can be more than one definition of a [...] class template (Clause [temp]) [...] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

  • each definition of D shall consist of the same sequence of tokens; and
  • [...]

If D is a template and is defined in more than one translation unit, then the preceding requirements shall apply both to names from the template's enclosing scope used in the template definition ([temp.nondep]), and also to dependent names at the point of instantiation ([temp.dep]). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

不同的 token 序列。

你可以轻松解决它,如Jarod42建议,将模板的两个定义放入一个未命名的命名空间,从而为它们提供内部链接。

关于c++ - 跨 TU 的类模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48399711/

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