使用模板链接错误 [英] Link error using templates
问题描述
我将函数转换为模板,并开始遇到此错误。我一定不了解模板的局限性。有人可以告诉我为什么会这样吗?
I converted a function to a template, and started getting this error. I must not be understanding a limitation of templates. Can someone tell me why this is broken?
我收到此错误:
Undefined symbols:
"bool foo<int>(int const&, int const&)", referenced from:
_main in file1.o
ld: symbol(s) not found
当我链接以下代码时。该代码已简化,但仍然失败。第一个文件包含:
When I link the following code. The code is simplified, but still fails. The first file contains:
#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文件的头文件中)显式定义为静态或内联。
For the reason Uri gave, template methods are usually defined in the header file. Because yours is a function and not a method of a class, explicitly define it (in the header file which may be included by more than one CPP file) as static or inline.
将其放入您的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代码现在可以看到模板函数的整个声明。
The cpp code now sees the whole declaration of the template function.
此处列出了其他解决方案:如何避免模板函数出现链接器错误?
Other solutions are listed here: How can I avoid linker errors with my template functions?
这篇关于使用模板链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!