Hi! I'm running Ubuntu 9.04 and using Code::Blocks as C++ IDE. I have the following code:

Temp.h:

#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

Temp.cpp:

#include "Temp.h"

template <typename T>
T Temp<T>::getDato () const { return _dato; }

template <typename T>
void Temp<T>::setDato (T d) { _dato = d; }

main.cpp:

#include "Temp.h"
#include <iostream>

using namespace std;

int main()
{
    Temp<double> temp(3.24);

    cout << temp.getDato() << endl;
    return 0;
}

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".
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!

Basically your template instantiation is in the wrong piece of code.
It should be in the Temp.cpp.

Why: To create an instance of a class you have to have all the methods available to the compiler. You can be doing absolutly anything with typename T. So it has to be in the cpp file. [You can have it in the .h file BUT you have to be VERY careful it is instantiated only once]

Yes, that's ok, if I put the instantiation in the .CPP it compiles ok. What I don't understand is why that code (with the instantiation in de .H) works under Windows / MinGW and don't in Linux / GCC.
(By the way, the teacher told me that I MUST put the instantiation in the .H and I don't want to explain him that that is WRONG =P ).

Tough. Try telling that to the standard committee. Section 13.10 tells us that when an template is explicitly instantiated it is necessary to create ALL the methods. Additionally the compiler is no required to resolve multiple instansiation hence it is wrong to put it in the .h

Windows has the whole project in VS, so it can play with the standard but if you try to link various dll's I suspect that it wouldn't work.
gcc works of a file by file system so you can't.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.