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)
{
//cod开发者_JAVA技巧e
}
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?
The usual problem. Have a look: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13.
Just put everything into a header file.
file.hpp
class ana
{
//code
public:
template <class T> bool method (T &Data)
{
//code
}
};
Include this in your main.cpp and it should work fine.
#include "file.hpp"
main()
{
//code
Ana* ann = new Ana();
if (ann->method(*ann)){//code}
}
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 .cpp
file. Its called explicit 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:
#ifndef __ANA_H__
#define __ANA_H__
template <class T>
class ana {
public:
bool method(T& data);
};
#endif
file.cpp:
#include <ana.h>
#include <iostream>
using namespace std;
template <typename T>
bool ana<T>::method(T& data) {
cout << "Data = " << data << endl;
if(data > 0) {
return true;
}
return false;
}
//explicit instantiation for avoidance of g++ linker errors.
template
bool ana<int>::method(int& data);
template
bool ana<double>::method(double& data)
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 int
and double
. The specs for your code should be such that method is never called for data types other than the above.
HTH,
Sriram
- You forgot to build
file.cpp
into the binary. - You should put the function template definition in the header, anyway.
You need to change the definition of your method()
method to be in the header file:
class ana
{
public:
template <class T>
bool method (T &Data)
{
// Do whatever you want in here
}
};
Check the following link out for a detailed explanation - http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
Just include cpp file in main.cpp like this: #include "ana.cpp" and you will not have errors.
精彩评论