模板实例在不同的翻译单元 [英] Template instance in different translation units
问题描述
据我所知,每个模板在每个翻译单元上都有不同的实例,为了我的理解,翻译单元大致是一个 cpp
文件。
As far as I know, each template have different instances on each translation unit, and for my understanding a translation unit is roughly a cpp
file.
所以,如果我有一个名为 test.hpp
的文件,包含以下内容:
So, if I have a file named test.hpp
with the following contents:
// test.hpp
template <typename T> void test()
{
static T t = T(0);
return t++;
}
对于每个翻译单元,我应该有一个不同的实例 test
,即使模板参数 T
是相同的。我决定测试它,所以我创建了以下文件(包括守卫被省略为了简洁):
For each translation unit I should have a different instance of test
even if the template parameter T
is the same in each of them. I've decided to test it so I've created the following files (include guards are omitted for the sake of brevity):
// a.hpp
namespace A { void f(); }
// a.cpp
#include <iostream>
#include "a.hpp"
#include "test.hpp"
namespace A
{
void f() { std::cout << test<int>(); }
}
// b.hpp
namespace B { void f(); }
// b.cpp
#include <iostream>
#include "b.hpp"
#include "test.hpp"
namespace B
{
void f() { std::cout << test<int>(); }
}
我们可以看到, a.cpp 和
实例使用
测试的
模板,但是以不同的翻译单位,因此执行以下程序: int
()
As we can see, both a.cpp
and b.cpp
uses the int
instance of the test()
template but in different translation units, so executing the following program:
// main.cpp
#include "a.hpp"
#include "b.hpp"
int main()
{
A::f();
B::f();
return 0;
}
我期待输出 00
但我得到 01
。我用来测试这个代码的IDE是MSVC2010 V10.0.4 SP1。
I was expecting an output of 00
but i get 01
instead. The IDE I'm using to test this code is MSVC2010 V10.0.4 SP1.
那么问题是什么呢?
- 我对模板和翻译单元的理解是否错误?或...
- 我对此测试代码做了错误。
推荐答案
我对模板和翻译单位的理解是否错误?
Is my understanding of the templates and translation units wrong?
错误。
模板函数的副本是每种类型和不是每个翻译单位创建的。
在您的情况下,对于 test< int>
,只创建一个副本,并且在所有TU中使用相同的副本。
In your case, for test<int>
only 1 copy is created and same is used across all the TUs.
这篇关于模板实例在不同的翻译单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!