c++ - 为什么只能在头文件中实现模板?

标签 c++ templates c++-faq

引用The C++ standard library: a tutorial and handbook:

The only portable way of using templates at the moment is to implement them in header files by using inline functions.



为什么是这样?

(澄清:头文件不是唯一的可移植解决方案。但是它们是最方便的可移植解决方案。)

最佳答案

注意:不必将实现放在头文件中,请参阅此答案末尾的替代解决方案。

无论如何,您的代码失败的原因是,在实例化模板时,编译器会使用给定的template参数创建一个新类。例如:

template<typename T>
struct Foo
{
    T bar;
    void doSomething(T param) {/* do stuff using T */}
};

// somewhere in a .cpp
Foo<int> f; 

阅读此行时,编译器将创建一个新类(我们将其称为FooInt),其等效于以下内容:
struct FooInt
{
    int bar;
    void doSomething(int param) {/* do stuff using int */}
}

因此,编译器需要访问方法的实现,以使用模板参数(在本例中为int)实例化它们。如果这些实现不在头文件中,则将无法访问它们,因此编译器将无法实例化模板。

一种常见的解决方案是将模板声明写入头文件中,然后在实现文件(例如.tpp)中实现该类,并将此实现文件包括在头文件的末尾。

oo
template <typename T>
struct Foo
{
    void doSomething(T param);
};

#include "Foo.tpp"

Foo.tpp
template <typename T>
void Foo<T>::doSomething(T param)
{
    //implementation
}

这样,实现仍与声明分开,但编译器可以访问。

替代解决方案

另一个解决方案是使实现分离,并显式实例化所需的所有模板实例:

oo
// no implementation
template <typename T> struct Foo { ... };

Foo.cpp
// implementation of Foo's methods

// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float

如果我的解释不够清楚,可以看看C++ Super-FAQ on this subject

关于c++ - 为什么只能在头文件中实现模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180729/

相关文章:

c++ - read方法从文件中返回最后一个对象两次

python - 谷歌应用引擎 : objects passed to a template changes their addresses in memory

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

C++ 删除 - 它删除了我的对象,但我仍然可以访问数据?

c++ - 有多少并发的 rtsp 流可以通过 WAN 可靠地直播 555 流

c++ - 指定扩展名文件的高效搜索算法 C/C++

c++ - 由引用 : what am I doing wrong? 引起的意外复制构造

c++ - 您可以在 C++ 中制作自定义运算符吗?

c++ - 类模板的非模板函数友元

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?