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

标签 c++ templates undefined-reference 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<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)实例化它们。如果这些实现不在 header 中,则无法访问它们,因此编译器将无法实例化模板。

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

Foo.h

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

#include "Foo.tpp"

Foo.tpp

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

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

替代方案

另一种解决方案是保持实现分离,并显式实例化您需要的所有模板实例:

Foo.h

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

相关文章:

c++ - 从文件中读取 SCons 环境设置

c++ - 如何让类在没有 getter 的情况下返回其他类型?

c++ - 智能指针的模板特化与普通指针完全一样

c++ - undefined symbol : memset, 版本 GLIBC_2.2.5

java - float 到 string 转换错误

c++ - 在C++中,为什么虚函数使类类型不符合聚合条件?

c++ - 获取 std::vector/std::array 的维数

Java 映射和集合在同一个 add 方法中

C++:未定义对命名空间中函数的引用

c++ - MinGW/G++/g95 链接错误 - libf95 未定义对 `MAIN_' 的引用