1

我正在阅读 C++ Primer 5th edition 这本书,我得到了这个:

使用模板时会生成实例化这一事实(第 16.1.1 节,第 656 页)意味着相同的实例化可能出现在多个目标文件中。当两个或多个单独编译的源文件使用具有相同模板参数的相同模板时,每个文件中都有该模板的实例化。

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

//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>应该只实例化一次,但我不知道如何在这个例子中使用这种技术。

4

1 回答 1

1

您将有明确的实例化

//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
于 2016-05-18T18:03:47.617 回答