2012-09-16 50 views
0

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?
Why can templates only be implemented in the header file?类方法来创建模板

也许我对于它只是太傻,但是这并没有为我工作:

foo.h中

#ifndef FOO_H 
#define FOO_H 

class Foo { 
public: 
    template<typename T> 
    void foo(T const &); 
}; 

#endif // FOO_H 

富.cpp

#include "Foo.h" 

template<typename T> 
void Foo::foo(T const &var) { 
    // do something useless 
} 

的main.cpp

#include "Foo.h" 

int main() { 
    int i; 
    Foo bar; 
    bar.foo(i); 
} 

我只是在Xcode 4.4.1编译但它返回我下面的链接错误:

Undefined symbols for architecture x86_64: 
    "void Foo::foo<int>(int const&)", referenced from: 
     _main in main.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

感谢您的答复!

+1

我们*字面上*刚刚有[这个非常相同的问题](http://stackoverflow.com/q/12446875/596781)...它的模板周日再次:-) –

回答

3

模板方法定义必须在实例化时可用。尝试将方法的定义放在头文件中。

+0

好奇,知道为什么你认为会工作。这是将实现与类的定义分开的标准方式,对吗? – Vikdor

+0

@Vikdor Right ...除非该方法是模板方法。 –

+0

谢谢!没有办法在* .cpp * -file中执行它? – qwertz