不同翻译单元中的模板实例
Template instance in different translation units
据我所知,每个模板在每个翻译单元上都有不同的实例,据我了解,翻译单元大致是一个 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
都使用了 test()
模板的 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。
那么问题是什么?
- 我对模板和翻译单元的理解有误吗?或者...
- 我这个测试代码有问题吗?
Is my understanding of the templates and translation units wrong?
是的。错了。
模板函数的副本是每个类型创建的,不是每个翻译单元。
在您的情况下,test<int>
只创建了 1 个副本,并且在所有 TU 中使用相同的副本。
据我所知,每个模板在每个翻译单元上都有不同的实例,据我了解,翻译单元大致是一个 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
都使用了 test()
模板的 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。
那么问题是什么?
- 我对模板和翻译单元的理解有误吗?或者...
- 我这个测试代码有问题吗?
Is my understanding of the templates and translation units wrong?
是的。错了。
模板函数的副本是每个类型创建的,不是每个翻译单元。
在您的情况下,test<int>
只创建了 1 个副本,并且在所有 TU 中使用相同的副本。