c++:什么是显式实例化

c++: what is explicit instantiation

我正在阅读 C++ primer 第 5 版这本书,我得到了这个:

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.

我不确定我是否理解正确所以我在这里做了一个例子:

//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

根据上面的段落,在这个例子中,Test_tpl被实例化(Test_tpl<int>)两次。现在如果我们使用显式实例化,Test_tpl<int> 应该只实例化一次,但我不知道如何在这个例子中使用这种技术。

您将使用

进行显式实例化

//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