2013-02-14 192 views
-2
main.o: In function `main': 
main.cpp:(.text+0x2f): undefined reference to `Foo<int>::display(int)' 
collect2: ld returned 1 exit status 

引起未定义参考

g++ -c *.cpp && g++ *.o -o foo 

foo.hpp

#ifndef FOO_H_ 
#define FOO_H_ 

template<typename T> 
class Foo { 
    private: 
    T ft_; 
    public: 
    Foo(const T & ft) : ft_(ft) { } 
    Foo display(T x); 
}; 

#endif 

foo.cpp

#include "foo.hpp" 
#include<iostream> 
using namespace std; 

template<typename T> 
Foo<T> Foo<T>::display(T x) { 
    // do some stuff - not too relevant 
    cout << "[" << x << "]"; 
    Foo<T> res(x); 
    return res; 
} 

main.cpp

#include<iostream> 
#include "foo.hpp" 
using namespace std; 

int main() { 
    Foo<int> f(42); 
    Foo<int> g = f.display(39); 
    return 0; 
} 

为什么?

P. S.与内联函数定义一起使用。每当函数的声明和定义被分成两个文件时就会出现问题...

+1

Yaaaaaawwwwwwwwn – 2013-02-14 14:07:26

+2

你忘了在你的C++书中读过那个告诉你不要在'.cpp'文件中定义函数模板的页面。 – 2013-02-14 14:08:11

+0

http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – 2013-02-14 14:10:49

回答

2

在C++中,您需要将模板化方法和函数的定义放入头文件中。

+1

那么在C++ 11中呢? – 2013-02-14 14:10:05

+0

@LightnessRacesinOrbit嗯看起来我一直对extern模板的含义感到困惑......我认为有人提议可以在'.cpp'文件中定义模板并认为它已进入。从答案中删除该模板。 – 2013-02-14 14:17:33

+0

也许你正在考虑'export',它实际上是从C++ 11中删除的,但从来没有工作过。 – 2013-02-14 14:18:46