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 インライン化された関数定義で動作します。関数の宣言と定義が2つのファイルに分割されるたびに問題が発生します...