【发布时间】:2015-06-04 17:11:33
【问题描述】:
据我所知,每个模板在每个翻译单元上都有不同的实例,据我了解,翻译单元大致是一个cpp 文件。
所以,如果我有一个名为 test.hpp 的文件,其内容如下:
// test.hpp
template <typename T> void test()
{
static T t = T(0);
return t++;
}
对于每个翻译单元,我应该有一个不同的 test 实例,即使模板参数 T 在每个翻译单元中都是相同的。我决定对其进行测试,因此我创建了以下文件(为简洁起见,省略了包括守卫):
// 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 和b.cpp 都使用int 模板的int 实例,但在不同的翻译单元中,因此执行以下程序:
// main.cpp
#include "a.hpp"
#include "b.hpp"
int main()
{
A::f();
B::f();
return 0;
}
我期待00 的输出,但我得到了01。我用来测试这段代码的IDE是MSVC2010 V10.0.4 SP1。
那么问题是什么?
- 我对模板和翻译单元的理解有误吗?或者...
- 我的测试代码有问题吗?
【问题讨论】:
标签: c++ templates translation-unit