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;
}
为什么?!
PS 适用于内联函数定义。每当函数的声明和定义被分成两个文件时,麻烦就来了……