Template instance in different translation units [duplicate]

痞子三分冷 提交于 2020-01-15 23:37:21

问题


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:


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.



来源:https://stackoverflow.com/questions/29367350/template-instance-in-different-translation-units

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!