2

i am using Qt5 creator , all the files are included in the project (the class "MyCounter" is created using the IDE wizard) i reduced my code to this one, and when i compile and run:

         undefined reference to MyCounter<int>::MyCounter()

main.cpp

#include <QCoreApplication>
#include"mycounter.h" //if include "mycounter.cpp" instead of "mycounter.h" works fine


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyCounter<int> x;
return a.exec();
}

mycounter.h

 #ifndef MYCOUNTER_H
 #define MYCOUNTER_H

 template<class T>
 class MyCounter
 {
   public:
      MyCounter();
 };

 #endif // MYCOUNTER_H

mycounter.cpp

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


  template<class T>
  MyCounter<T>:: MyCounter()
 {
  std::cout<<"somthing...";
}
  • [why-can-templates-only-be-implemented-in-the-header-file](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – yngccc Jun 30 '13 at 15:11

1 Answers1

2

If you have a template, the entire implementation should be in the header file.

You can't (sensibly) have template classes and functions implemented separately (well, you can instantiate all of the specializations separately in the .cpp file, but why would you do that? After all, you cannot possibly think about every possible specialization, so there's no point in doing that...)

  • *You cannot possibly think about every possible specialization*, Yes you can as long as the implementation you provide is restrictive in terms of the types it supports. – Alok Save Jun 30 '13 at 15:16
  • @AlokSave I'm not sure I get it. How would you restrict the specialization to certain types? And more importantly: why? And even more importantly: would the implementation of all possible specializations a better solution than just keeping it all in the header? –  Jun 30 '13 at 15:17
  • Because it allows you to tell the users of your code that your code works and supports instantiations for only certain types. Also, it stops them from using the code for such types. And it is a good thing IMO. – Alok Save Jun 30 '13 at 15:21
  • so when i define the whole implimentaion "MyCounter class" in on file ".h" can i still deploy it in DLL and the effects would still be the same as i separate them – user1926574 Jun 30 '13 at 15:25
  • @user1926574 Yes, except that the class would work only for the types you specialized it for. –  Jun 30 '13 at 15:28