[Solved] simple template class is not compiled
-
Good day!
I written simple template class, but it is not compiled in the current view:
MyClass.h
@#ifndef MYCLASS_H
#define MYCLASS_Htemplate <class T> class MyClass
{
public:
MyClass();
T x;
};#endif // MYCLASS_H@
MyClass.cpp
@#include "MyClass.h"template < class T > MyClass<T>::MyClass()
{
x = 0;
}
@
main.cpp
@#include <QtCore/QCoreApplication>
#include <QDebug>
#include "MyClass.h"int main(int argc, char *argv[])
{
MyClass<int> a;
a.x = 10;
qDebug() << a.x;
return 0;
}@
I get the next error:
@D:..\template_class1\main.cpp:7: error: undefined reference to `MyClass<int>::MyClass()'@But if I write all in the one file then all of it is successfully compiled:
@#include <QtCore/QCoreApplication>
#include <QDebug>template <class T> class MyClass
{
public:
MyClass();
T x;
};template < class T > MyClass<T>::MyClass()
{
x = 0;
}int main(int argc, char *argv[])
{
MyClass<int> a;
a.x = 10;
qDebug() << a.x;
return 0;
}@Why is not compiled the first variant?
Say me please, where is my error?——————
Best regards,
Galiego710 -
Since a template is only a pattern to generate code in the first case the compiler can't "see" the implementation of your template class - you include the header and the compiler needs the implementation to generate the code for MyClass with int instead of T
Read more "here":http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12 -
I will read it.
Thank you very much for fast answer and very useful link!