我将函数转换为模板,然后开始出现此错误。我不能理解模板的限制。谁能告诉我为什么它坏了?
我收到这个错误:
Undefined symbols:
"bool foo<int>(int const&, int const&)", referenced from:
_main in file1.o
ld: symbol(s) not found
当我链接以下代码时。代码被简化了,但仍然失败。第一个文件包含:
#include <iostream>
template <class T> bool foo (const T&, const T&);
int main ()
{
int left = 1;
int right = 2;
if (foo <int> (left, right))
std::cout << "foo!" << std::endl;
return 0;
}
第二个文件包含:
template <class T> bool foo (const T& left, const T& right)
{
return true;
}
最佳答案
Uri给出的原因,模板方法通常定义在头文件中。因为你的是一个函数而不是一个类的方法,所以明确地将它定义为静态或内联(在可能被多个 CPP 文件包含的头文件中)。
把它放在你的 foo.h 中
template<class T> inline bool foo (const T& left, const T& right)
{
return true;
}
把这个放在你的 main.cpp 中
#include <iostream>
#include "foo.h"
int main ()
{
int left = 1;
int right = 2;
if (foo <int> (left, right))
std::cout << "foo!" << std::endl;
return 0;
}
cpp 代码现在可以看到模板函数的整个声明。
此处列出了其他解决方案:How can I avoid linker errors with my template functions?
关于c++ - 使用模板链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/550219/