2012-09-16 46 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