foo.h #ifndef _FOO #define _FOO template <class T> class foo{ private: T f; public: void setFoo(T val); T getFoo(); }; #endif
foo.cpp #include "foo.h" template <class T> void foo<T>::setFoo(T val){ f = val; } T foo<T>::getFoo(){ return f;
fooImpl.cpp #include "foo.cpp" template foo<int>;
goodtestFoo.cpp #include <iostream> using namespace std; #include "fooImpl.cpp" int main(){ foo<int> myFoo; myFoo.setFoo(42); cout << "we got " << myFoo.getFoo() << endl; return 0; }
badTestFoo.cpp #include <iostream> using namespace std; #include "fooImpl.cpp" int main(){ foo<int> myFoo; myFoo.setFoo(42); cout << "we got " << myFoo.getFoo() << endl; foo<double> anotherFoo; //OOPS! – not instantiated anotherFoo.set(64.5); cout << "we got " << anotherFoo.getFoo() << endl; return 0; }
compile, run goodtestfoo linux3[106] % g++ -o goodtestfoo goodtestfoo.cpp fooImpl.cpp linux3[107] % goodtestfoo we got 42
compiling badtestfoo linux3[104] % g++ -o badtestfoo badtestfoo.cpp fooImpl.cpp badtestfoo.cpp: In function `int main()': badtestfoo.cpp:10: no matching function for call to `foo<double>::set(double)'