冲突的模板定义和ODR [英] Conflicting template definitions and ODR

查看:85
本文介绍了冲突的模板定义和ODR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有两个不同的翻译单位a.cpp

Imagine a situation where I have two distinct translation units a.cpp

#include <iostream>

double bar();

template <typename T>
T foobar(T t) {
    return t;
}

int main() {
    std::cout << "foobar called from b.cpp: " << bar() << '\n';
    std::cout << "foobar called from a.cpp: " << foobar(1.) << '\n';
}

和b.cpp:

template <typename T>
T foobar(T t) {
    return t + 1.;
}

double bar() {
    return foobar(1.);
}

我知道对于模板来说,ODR是有例外的,即编译器将标记实例化的函数模板,并在链接过程中剔除一个模板.我注意到,编译器实际上并不关心在不同翻译单元处生成的此类实例化代码实际上是相同的还是至少等效的.

I know that for templates, there are exceptions to the ODR, i.e. the compiler will mark instantiated function templates as such and will strike out all but one during the linking process. I noticed that the compiler doesn't actually care whether the generated codes of such instantiations at different translation units are actually identical or at least equivalent.

在上面的代码中,就是这种情况.编译,链接并运行时

In the code above, this is the case. When compiling, linking and running with

c++ a.cpp b.cpp -o result -std=c++17 && ./result

它将产生结果

foobar called from b.cpp: 1
foobar called from a.cpp: 1

因此,显然,目标文件b.o中的实例化被a.o中的那个实例所取代.与b.cpp和链接的a.cpp进行编译和链接时,例如

So apparently, the instantiation inside the object file b.o got thrown away in favour for that one from a.o. When compiling and linking with b.cpp and a.cpp swapped, like

c++ b.cpp a.cpp -o result -std=c++17 && ./result

结果将是

foobar called from b.cpp: 2
foobar called from a.cpp: 2

因此发生了完全相反的事情:在待链接目标文件列表中首先提到的实例化将继续存在.是否在标准中的某处定义了这种行为?根据构建系统的不同,提到目标文件的顺序可能是任意的,但是,在这样的示例中,它导致了截然不同的程序并可能导致繁琐的错误.即使我尝试通过添加

so the exact opposite happens: the instantiation that got mentioned first in the list of to-be-linked object files will be the one that survives. Is such a behaviour defined somewhere within the standard? Depending on the build system, the order in which the object files are mentioned can be rather arbitrary, but, as in such examples it leads to very different programs and possibly cumbersome bugs. Even if I try to explicitely instantiate the version from a.cpp by adding

template double foobar<double>(double);

当在链接器列表中的a.o之前提到b.o时,a.cp​​p中的foobar<>模板将无法生存.

it will not make the foobar<> template from a.cpp survive when mentioning b.o before a.o in the linker list.

推荐答案

我知道对于模板来说,ODR有一些例外情况

I know that for templates, there are exceptions to the ODR

模板的ODR也不例外,只是模板功能是 inline .

There are no exceptions for ODR for template, it is just that template function are inline.

您的程序违反了ODR.
常规的内联函数会遇到类似的问题.

And your program has ODR violation.
You would have similar issue with regular inline functions.

这篇关于冲突的模板定义和ODR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆