模板函数产生未定义的引用错误
Template Function yields undefined reference error
我正在尝试为具有任何类型的坐标(int,float等(的矢量实现曼哈顿距离的模板函数,以C++为单位。
所以我有这个:
template <typename T>
T manhattan_distance(std::vector<T> v1, std::vector<T> v2) {
//implementation
}
尝试使用它(在另一个文件中(时,我执行以下操作:
std::vector<int> v1 = [1,2,3];
std::vector<int> v2 = [4,5,5];
int res = manhattan_distance(v1,v2);
make
-ing 时,出现此错误:
undefined reference to `int manhattan_distance<int>(std::vector<int, std::allocator<int> >, std::vector<int, std::allocator<int> >)'
问题出在哪里?该函数不在类中。我错过了什么吗?提前感谢!
编译 cpp 文件时,模板代码必须可用,不能只在标头中包含声明。
原因是编译器在读取模板时不会生成任何代码;只有当你使用它时,它才会构建它的实例。模板函数的声明不足以生成代码。
您还需要在头文件中具有实现。这是模板编程的一个众所周知的缺点。
相关文章:
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++引用错误
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 只有级联分类器会发出未定义的引用错误
- 2个模板化类的非模板友元函数未定义引用错误
- C/C++ 取消引用错误:在空检查之前取消引用
- 为什么我的C++代码无法编译,出现未定义的引用错误
- 我的代码中C++未定义的引用错误?
- 模板专用化会导致未定义的引用错误
- .cpp文件中未定义的引用错误
- c++ 中目录中文件的未定义引用错误
- Opencv4 使用 pkg-config 给出未定义的引用错误
- 使用Cygwin C++时出现未定义的引用错误,为什么我的文件没有链接?
- 共享指针取消引用错误
- 编译简单的多文件类程序时出现未定义的引用错误
- 模板函数产生未定义的引用错误
- 调用提取重加载器会产生对"运算符"的未定义引用错误>>
- 如何修复"未定义的引用"错误 opencv 和 g++
- 未定义的引用错误,我该怎么办?