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.与内联函数定义一起使用。每当函数的声明和定义被分成两个文件时就会出现问题...
Yaaaaaawwwwwwwwn – 2013-02-14 14:07:26
你忘了在你的C++书中读过那个告诉你不要在'.cpp'文件中定义函数模板的页面。 – 2013-02-14 14:08:11
http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – 2013-02-14 14:10:49