2009-02-15 58 views
1

我将函数转换为模板,并开始出现此错误。我不能理解模板的限制。有人能告诉我为什么这是坏的?当我链接下面的代码使用模板链接错误

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; 
} 

回答

3

由于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?

+0

static/inline mods没有任何作用。我很难过。 – 2009-02-15 03:03:59

2

它已经多年,因为我做了很多C++,但我认为你遇到不同的编译的问题。模板在编译时被实例化,而不是链接。

因此,当您调用foo()时,您并没有真正实例化模板,因为没有生成新的函数代码,您只需创建链接器必须解决的符号。

但是,当编译第二个文件时,它只有模板,并且它从不实例化,因此不会生成实际处理整数的foo()版本。因此,当你把所有东西链接在一起时,你会得到错误。

我不是100%确定该怎么做,但我怀疑你需要强制在第二个文件(假设它是C++)中用ints强制实例化foo()。 我只使用类模板,而不是函数模板,我敢肯定这里有人会给你几个确切的代码...