Template instance in different translation units [

2019-08-09 17:56发布

This question already has an answer here:

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.

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++;
}

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>(); }
}

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;
}

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.

So what's the question?

  • Is my understanding of the templates and translation units wrong? or...
  • I did something wrong with this test code?

1条回答
冷血范
2楼-- · 2019-08-09 18:26

Is my understanding of the templates and translation units wrong?

Yes. It's wrong.
A copy of template function is created per type and not per translation unit.

In your case, for test<int> only 1 copy is created and same is used across all the TUs.

查看更多
登录 后发表回答