what is wrong with this template?

Hi,

I have defined a test class "Pair" with a template but I am getting compilation error. Without template, it compiles fine. So, something is coming due to template. I wonder what is wrong. The error is:
1
2
3
4
5
6
7
CMakeFiles/main.exe.dir/main.cxx.o: In function `main':
main.cxx:7: undefined reference to `Pair<float>::set_element(int, float)'
main.cxx:8: undefined reference to `Pair<float>::set_element(int, float)'
collect2: error: ld returned 1 exit status
make[2]: *** [main.exe] Error 1
make[1]: *** [CMakeFiles/main.exe.dir/all] Error 2
make: *** [all] Error 2 


Pair.h file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef __Pair__
#define __Pair__

#include<iostream>
using namespace std;

template <class T>
class Pair
{
        public:
                Pair() {};
                Pair(T first, T second);

                void set_element(int pos, T value);

        private:
                T first, second;
};
#endif 

Pair.cxx file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "Pair.h"
#include<cstdlib>

template <class T>
Pair<T>::Pair(T fi, T se)
{
        first = fi;
        second = se;
}

template <class T>
void Pair<T>::set_element(int pos, T value)
{
        if(pos == 1) first = value;
        else if(pos == 2) second = value;
        else {
                cout << "Error: Illigal pair position.\n";
                exit(1);
        }
}

main.cxx file
1
2
3
4
5
6
7
8
9
10

#include "Pair.h"

int main()
{
        Pair<float> score;

        score.set_element(1, 3.0);
        score.set_element(2, 2.0);
}

Last edited on
However, defining "set_element" function inline in the header file works.
1
2
3
4
5
6
7
template <class T>
inline void Pair<T>::set_element(int pos, T value) 
{
    if(pos == 1) first = value; 
    else if(pos == 2) second = value; 
    else exit(-1);
}
Last edited on
You know, you could just make 'first' and 'second' public. Then I could just
1
2
3
Pair<int> p;
p.first = 10;
p.second = -22;
I found somewhere http://www.parashift.com/c++-faq-lite/templates.html that one can't define the class function inside .cxx file in a conventional way, it has to be defined inside .h file.
I found somewhere http://www.parashift.com/c++-faq-lite/templates.html that one can't define the class function inside .cxx file in a conventional way, it has to be defined inside .h file.

Yes, that's correct. At the point where the compiler creates the class for a particular type, it needs to have the entire definition of the class available. This means that the entire definition of the class needs to be included in the translation unit.
Topic archived. No new replies allowed.