问题
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...";
}
回答1:
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...)
来源:https://stackoverflow.com/questions/17391770/undefined-reference-to-c-class-constructor