Template of ingredient class
I want create class with pattern of function. When I add definition of function to *.cpp file and call it in mainwindow.cpp, I have bugs:
Code:
mainwindow.o:-1: error: In function `ZN10MainWindowC2EP7QWidget':
mainwindow.cpp:6: undefined reference to `readmemory::readmemory()'
mainwindow.o:-1: error: In function `ZN10MainWindowC1EP7QWidget':
mainwindow.cpp:6: undefined reference to `readmemory::readmemory()'
mainwindow.o:-1: error: In function `ZN10MainWindow11startSearchEv':
mainwindow.cpp:46: undefined reference to `void readmemory::test<int>(int)'
:-1: error: collect2: ld returned 1 exit status
It's my exemplary code:
class.h
Code:
class Pattern{
template<typename T> void function(T);
};
class.cpp
Code:
template<typename T>
void Pattern::function(T a)
{
//code
}
mainwindow.h
Code:
Pattern patternClass;
int a;
patternClass.function(a);
I tried use "export" like in Visual Studio and include class.cpp to class.h, but it doesn't work. Is it possible to use template like in my test code?
Re: Template of ingredient class
You declare a template... this makes the compiler happy.
But at link time, the calls can't be resolved as those functions have not been implemented (only called):
You have to tell the compiler that a specialization for int has to be compiled.
possible way to do it:
add
Code:
template<> void Pattern::function(int a)
{
//code
}
to class.cpp
or just leave the implementation in class.hpp and save you the trouble.
(putting specializations into the .cpp will reduce code bloat, though.)
Re: Template of ingredient class
So, when i want use my function like:
Code:
double a;
patternClass.function(a);
Must I define new function with argument double? If it's true, I can glut function with the same result.