[Solved] Template function in seperate cpp file
-
wrote on 9 May 2013, 09:02 last edited by
I use Qt 5.0.1 and created simple Qt Gui Application. Then I created QtHarrixLibrary.cpp:
@#include "QtHarrixLibrary.h"template <class T> T funcT(T x)
{
return 2*x;
}int func(int x)
{
return 2*x;
}
@and QtHarrixLibrary.h files:
@#ifndef QTHARRIXLIBRARY_H
#define QTHARRIXLIBRARY_Htemplate <class T> T funcT(T x);
int func(int x);
#endif // QTHARRIXLIBRARY_H
@Then I added files in project (Add Existing Files...), added in mainwindow.cpp code:
@#include "QtHarrixLibrary.h"@Then added pushButton and textEdit. And pushButton has slot:
@void MainWindow::on_pushButton_clicked()
{
int x=5;int y=func(x); ui->textEdit->insertPlainText(QString::number(y)+"\n"); y=funcT(y); ui->textEdit->insertPlainText(QString::number(y)+"\n");
}
@And I have errors:
C:\Qt\untitled4\mainwindow.cpp:26: error: undefined reference to `int funcT<int>(int)'
collect2.exe:-1: error: error: ld returned 1 exit statusWhen I use only function func program is working. When I don't use seperate cpp file and add funcT in mainwindow.cpp program ia working.
How fix it?
-
wrote on 9 May 2013, 09:25 last edited by
Hi,
template functions and classes shall be known to the compiler at Compile Time not at Link Time.
When you use templates you can
Include template implementations in header file
Define a external source included in header file
Example 1
QtHarrixLibrary.h
@
#ifndef QTHARRIXLIBRARY_H
#define QTHARRIXLIBRARY_Htemplate <class T> T funcT(T x)
{
return 2*x;
}int func(int x);
#endif // QTHARRIXLIBRARY_H
@QtHarrixLibrary.cpp
@
#include "QtHarrixLibrary.h"int func (int x)
{
return 2*x;
}
@Example 2
QtHarrixLibrary.h
@
#ifndef QTHARRIXLIBRARY_H
#define QTHARRIXLIBRARY_Htemplate <class T> T funcT(T x);
int func(int x);
#include "QtHarrixLibrary.tpp"
#endif // QTHARRIXLIBRARY_H
@QtHarrixLibrary.cpp
@
#include "QtHarrixLibrary.h"int func (int x)
{
return 2*x;
}
@QtHarrixLibrary.tpp
@
template <class T>
T funcT (T x)
{
return 2*x;
}
@Last TIP:
use
@template <typename T>@instead of
@template <class T>@
-
wrote on 11 May 2013, 09:29 last edited by
Thank you so much! Everything works!
3/3