模板函数产生未定义的引用错误

Template Function yields undefined reference error

本文关键字:引用 错误 未定义 函数      更新时间:2023-10-16

我正在尝试为具有任何类型的坐标(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 文件时,模板代码必须可用,不能只在标头中包含声明。
原因是编译器在读取模板时不会生成任何代码;只有当你使用它时,它才会构建它的实例。模板函数的声明不足以生成代码。

您还需要在头文件中具有实现。这是模板编程的一个众所周知的缺点。