Reputation: 12371
I'm reading the book C++ primer 5th edition and I got this:
The fact that instantiations are generated when a template is used (§ 16.1.1, p. 656) means that the same instantiation may appear in multiple object files. When two or more separately compiled source files use the same template with the same template arguments, there is an instantiation of that template in each of those files.
I'm not sure if I got it correctly so I made an example here:
//test_tpl.h
template<typename T>
class Test_tpl
{
public:
void func();
};
#include "test_tpl.cpp"
//test_tpl.cpp
template<typename T>
void Test_tpl<T>::func(){}
//a.cpp
#include "test_tpl.h"
// use class Test_tpl<int> here
//b.cpp
#include "test_tpl.h"
// use class Test_tpl<int> here
According to the paragraph above, in this example, Test_tpl is instantiated(Test_tpl<int>
) twice. Now if we use explicit instantiation, Test_tpl<int>
should be instantiated only once, but I don't know how to use this technique for this example.
Upvotes: 1
Views: 228
Reputation: 217135
You will have explicit instantiation with
//test_tpl.h
template<typename T>
class Test_tpl
{
public:
void func();
};
//test_tpl.cpp
#include "test_tpl.h"
template<typename T>
void Test_tpl<T>::func(){} // in cpp, so only available here
template void Test_tpl<int>::func(); // Explicit instantiation here.
// Available elsewhere.
//a.cpp #include "test_tpl.h"
// use class Test_tpl<int> here
//b.cpp #include "test_tpl.h"
// use class Test_tpl<int> here
Upvotes: 1