Placing member function code for templated class in seperate source files

Hey everyone, I'm trying to write a templated class and place member function code outside of the class definition. I'm using Dev C++ with the gcc compiler. When I try to compile my code, i get a linker error

[Linker error] undefined reference to 'foo<int>::sum()'
Id returned 1 exit status

I can seperate member function source files from the class definition source file if i'm not using a templated class, but I can't do it when I try to use a templated class. Here's the contents of my source files



main.cpp source file...


#include <iostream>
#include "foo.h"

using namespace std;

int main(int argc, char *argv[])
{

foo<int> myfoo;
myfoo.x = 1;
myfoo.y = 2;
myfoo.z = 3;

cout << myfoo.sum() << endl;

system("PAUSE");
return EXIT_SUCCESS;
}




foo.h source file...


template <typename T>
class foo {

public:
T x;
T y;
T z;

T sum();

};




sum.cpp source file...


#include "foo.h"

template <typename T>
T foo<T>::sum() {
return x + y + z;
}


Now if I take the contents of "sum.cpp" and stick it to the end of "foo.h" it compiles fine. It's just when i seperate the source files that I get a linker error. I don't want to do this, however, because it increases compile time by quite a bit especially when I have a big program. (i think it's b/c the my IDE compiles .cpp files only once but has to re-comile .h files everywhere they're included but not entirely sure)
You can't. You have to put them all in the header file.

As for your compilation length, it's not that the .h files are compiled, it's that all the .cpp files where they are included have to recompiled.

Also, Dev C++ is really old, you should probably get a newer IDE/compiler.
Topic archived. No new replies allowed.