Seperate Compilation of Template in Dev C++

Dear All,
Let's say I have the following two functions in main.cpp.

template<class T>
T addition(T a, T b);
{
return a+b;
}

template<class TA, class TB>
Ta subtraction(TA a, TB b);
{
return a-b;
}

int main()
{
return 0;
}

I am using Dev C++. (Yes... I know... I will change to Code::Block later...) And I want to put the function header, function implementation and main.cpp in three separate files... How exactly should I do it? I know how to do separate compilation for programs without using templates. However, in this case with templates used, where should I put the two lines of template<class...>?

Thanks.

Bosco
For templates you use header files only.

main belongs to main.cpp

put addition() and subtraction() to a.h/s.h (or so). and no cpp
Oh that's so odd... OK

If that's the case, is it actually OK to for me to put all other function implementations in header files even if they are not templates? (Although I wouldn't do that, but is that theoretically OK?)

Bosco
No, don't put implementations into headers(if you do so you may get a linker error: multiple definitions). Only template and inline functions belong there.

In the header you need to put the prototype/declaration of a function/class/struct. E.g.:

foo.h
1
2
struct f { int x; };
int foo();


foo.cpp
1
2
3
4
int foo()
{
  return 0;
}
Last edited on
OK, just implementation of template functions in header files then, all other implementations in .cpp, thanks.
Hello coder777 and all,
I just tried it out, it seems that putting the template function as well as its implementation in the header file does not work (in Dev C++)! However, it is fine if I just place the whole declaration in a .cpp separated from main.cpp. Could there be something wrong here?
Regards,
Bosco
Topic archived. No new replies allowed.