0

I have some code:

file.h:

#ifndef SAKE_H_INCLUDED
#define SAKE_H_INCLUDED
template <class T>

void swapq(T& a, T& b);

#endif // SAKE_H_INCLUDED

file.cpp:

#include "file.h"

template <class T>
void swapq(T& a, T& b){
   T temp=a;
   a=b;
   b=temp;
}

main.cpp:

#include <iostream>
#include "file.h"
using namespace std;


int main()
{

  int a=3, b=2;
  swapq(a,b);
  cout<<a<<" "<<b<<endl;
  return 0;
}

So when I built it, the compiler show me a error:

||=== Build: Release in test (compiler: GNU GCC Compiler) ===|
obj/Release/main.o||In function `main':|
 main.cpp:(.text.startup+0x2d)||undefined reference to `void 
swapq<int>(int&, int&)'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 
second(s)) ===|

I deleted "template " and replaced "T" in void function with "int" and it built successfully. How can I use template in a "file.h" and "file.cpp" so that I can swap two varible with different datatypes ?

Sake
  • 96
  • 5
  • It's not a full duplicate. There is a valid use case with `extern template` in the `file.h`, instantiate templates for the specific types in the `file.cpp`, and usage of the pre-instantiated template it in `main.cpp`. – bobah Sep 03 '18 at 09:55
  • @bobah IIRC all these cases are also explained and answered there. – πάντα ῥεῖ Sep 03 '18 at 09:56
  • I'm a beginner, so I read that link and I don't understand it. I don't see the same problem. So you can fix my code ? – Sake Sep 03 '18 at 10:14
  • @Sake - template is not the actual code, but the instantiation of the template (when you use the template) is the actual code. To generate the code the compiler needs to “see” the definition of the template, so generally speaking you should either have it in the header file (that you include) or also include the cpp file. Alternatively read about extern templates, they may be what you are after. – bobah Sep 03 '18 at 10:26
  • @πάνταῥεῖ - not for a beginner – bobah Sep 03 '18 at 10:26
  • @bobah Including a .cpp file will screw up most build systems, that's bad advice. – πάντα ῥεῖ Sep 03 '18 at 10:28
  • @πάνταῥεῖ - you can give it a different extension (icc, etc.) to have cmake / ide-s happy, some projects do that (I think even some boost libs). But I agree, it’s a questionable practice, I’d rather stick with headers and `extern template`. – bobah Sep 03 '18 at 10:34
  • @bobah Sure, I know that. – πάντα ῥεῖ Sep 03 '18 at 10:35
  • thank you for helping me :3 – Sake Sep 03 '18 at 10:59

0 Answers0