PDA

View Full Version : Template of ingredient class



Trok
21st August 2009, 10:50
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:


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


class Pattern{
template<typename T> void function(T);
};


class.cpp


template<typename T>
void Pattern::function(T a)
{
//code
}


mainwindow.h


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?

caduel
21st August 2009, 12:51
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

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.)

Trok
21st August 2009, 13:27
So, when i want use my function like:


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.