Why do I get quot;unresolved external symbolquot; errors when using templates?(为什么我得到“未解析的外部符号?使用模板时出错?)
问题描述
当我使用模板为类编写 C++ 代码并在源 (CPP) 文件和头 (H) 文件之间拆分代码时,在链接尽管目标文件被正确构建并包含在链接中,但最终可执行文件.这里发生了什么,我该如何解决?
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening here, and how can I fix it?
推荐答案
模板化的类和函数在使用之前不会被实例化,通常在单独的 .cpp 文件(例如程序源)中.使用模板时,编译器需要该函数的完整代码才能使用适当的类型构建正确的函数.但是,在这种情况下,该函数的代码在模板的源文件中有详细说明,因此不可用.
Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for that function is detailed in the template's source file and hence unavailable.
作为所有这些的结果,编译器只是假设它是在别处定义的,并且只插入对模板化函数的调用.在编译模板的源文件时,程序源中使用的特定模板类型并未在那里使用,因此它仍然不会生成函数所需的代码.这会导致无法解析的外部符号.
As a result of all this the compiler just assumes that it's defined elsewhere and only inserts the call to the templated function. When it comes to compile the template's source file, the specific template type that is being used in the program source isn't used there so it still won't generate the code required for the function. This results in the unresolved external symbol.
对此可用的解决方案是:
The solutions available for this are to:
- 包括完整的定义中的成员函数模板的头文件并且没有模板的源文件,
定义所有的成员函数模板的源文件为内联"(更新:[这不适用于 Visual Studio 2017+]),或定义成员模板源中的函数使用导出"关键字.不幸的是,这不受支持(更新:这已从 C++11 的标准中删除.)
- include the full definition of the member function in the template's header file and not have a source file for the template,
define all the member functions in the template's source file as "inline"(Update: [this does not work on Visual Studio 2017+]), ordefine the member functions in the template's source with the "export" keyword. Unfortunately this isn't supported by a lot of compilers.(Update: this has been removed from the standard as of C++11.)
当编译器尝试在程序源代码中构建类型化函数时,通过让编译器访问模板化函数的完整代码,1 和 2 基本上都解决了这个问题.
Both 1 and 2 basically address the problem by giving the compiler access to the full code for the templated function when it is attempting to build the typed function in the program source.
这篇关于为什么我得到“未解析的外部符号"?使用模板时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我得到“未解析的外部符号"?使用模板
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01