help me use template class

here is my code for pair.cpp and pair.h:
pair.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
  1 #include <iostream>
  2 using namespace std;
  3
  4 template <typename type>
  5 class homoPair{
  6
  7 private:
  8     type _first;
  9     type _second;
 10
 11 public:
 12     homoPair(type, type);
 13     type getFirst();
 14     type getSecond();
 15 };
 16
 17
 18
 19 template <typename type1, typename type2>
 20 class heteroPair{
 21
 22 private:
 23     type1 _first;
 24     type2 _second;
 25
 26 public:
 27     heteroPair(type1, type2);
 28     type1 getFirst();
 29     type2 getSecond();
 30 };


pair.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  1 #include <iostream>
  2 #include "pair.h"
  3 using namespace std;
  4
  5 template <typename type>
  6 homoPair<type>::homoPair(type first, type second){
  7     _first = first;
  8     _second = second;
  9 }
 10
 11 template <typename type>
 12 type homoPair<type>::getFirst(){
 13     return _first;
 14 }
 15
 16 template <typename type>
 17 type homoPair<type>::getSecond(){
 18     return _second;
 19 }
 20
 21
 22 template <typename type1, typename type2>
 23 heteroPair<type1, type2>::heteroPair(type1 first, type2 second){
 24     _first = first;
 25     _second = second;
 26 }
 27
 28 template <typename type1, typename type2>
 29 type1 heteroPair<type1, type2>::getFirst(){
 30     return _first;
 31 }
 32
 33 template <typename type1, typename type2>
 34 type2 heteroPair<type1, type2>::getSecond(){
 35     return _second;
 36 }


and main function
1
2
3
4
5
6
7
8
9
10
11
12
  1 #include <iostream>
  2 #include <string>
  3 #include "pair.h"
  4 using namespace std;
  5
  6 int main(){
  7     heteroPair<double, int> hep(20, 49);
  8
  9     cout << hep.getFirst() << " is " << hep.getSecond() << endl;
 10
 11     return 0;
 12 }


when I compile, i get the error msg "test.cpp:(.text+0x2a): undefined reference to `homoPair<double>::homoPair(double, double)'", i am very confused. can anyone explain why this error occurs?
thanks a lot.
It looks like that you have one more module in the project that you did not show here.
When dealing with templates, they need to be compiled with your program, not separately. The way to correct this is to either #include pair.cpp at the bottom of pair.h and remove pair.cpp from your project/compiler command or you can just copy/paste the code from pair.cpp to pair.h and eliminate pair.cpp altogether.
Topic archived. No new replies allowed.