Results 1 to 5 of 5
Hi! I'm running Ubuntu 9.04 and using Code::Blocks as C++ IDE. I have the following code:
Temp.h:
Code:
#ifndef TEMP_H_INCLUDED
#define TEMP_H_INCLUDED
template <typename T>
class Temp {
public:
Temp ...
- 10-01-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 2
Ubuntu C++ explicit instantiation
Hi! I'm running Ubuntu 9.04 and using Code::Blocks as C++ IDE. I have the following code:
Temp.h:
Temp.cpp:Code:#ifndef TEMP_H_INCLUDED #define TEMP_H_INCLUDED template <typename T> class Temp { public: Temp (T d = T(0)): _dato(d) {} T getDato () const; void setDato (T d); private: T _dato; }; template class Temp<double>; #endif // TEMP_H_INCLUDED
main.cpp:Code:#include "Temp.h" template <typename T> T Temp<T>::getDato () const { return _dato; } template <typename T> void Temp<T>::setDato (T d) { _dato = d; }
As you can see, I'm trying to use explicit instantiation of the template in the header file, but when I try to compile, the linker shows me "undefined reference to Temp<double>::getDato() const".Code:#include "Temp.h" #include <iostream> using namespace std; int main() { Temp<double> temp(3.24); cout << temp.getDato() << endl; return 0; }
The weird thing is that this code works in Windows with MinGW and GCC. In Ubuntu, it works if I put the template instantiation on the end of the Temp.cpp file.
I know I can / should put all the template's implementation on the header file and that will work, but this is for an university's work and they ask me to separate the implementation.
I'll apreciate any help or explanation!
- 10-01-2009 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
This is pretty bogus usage/implementation of templates. FWIW, you really need to make sure that all template code instantiation is inline. The compiler needs to see the implementation at the point you use it. That it worked on some C++ implementations is just plain luck.
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 10-01-2009 #3Just Joined!
- Join Date
- Oct 2009
- Posts
- 2
Sorry, I didn't understand what you mind with this "you really need to make sure that all template code instantiation is inline".
I know that this is not the best way of use templates, but is the way the teachers want, and it's hard to make them understand it. Specially because, AFAIK, there isn't a "standard" way for this.
(PD: Sorry if my english is not correct, I'm from Argentina)
- 10-01-2009 #4
- 10-02-2009 #5Just Joined!
- Join Date
- Jun 2009
- Location
- Toronto
- Posts
- 18
You could seperate the implementation into another header file like Temp_impl.h and then include it before the explicit instantiation.


Reply With Quote
