I am currently working in Ubuntu9.10 – c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
file.h
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
file.cpp
//code
template <class T>
bool ana::method(T &Data)
{
//code
}
I’ve created the .a file.
In test.cpp:
//code
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
After compiling with g++ test.cpp -o test libfile.a I have the error: undefined reference to bool.... Why? Is there another way to create a generic object?
Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the
.cppfile. Its calledexplicit instantiation.This will take care of linker errors. I tried some code, and this seems to work, based on what you have given:file.h:
file.cpp:
One of the downsides of using this method is that these lines will have to be included for every data type that you want this function to support. So, now the method function will run ONLY for
intanddouble. The specs for your code should be such that method is never called for data types other than the above.HTH,
Sriram