0

I have a template class that takes 2 data types T1 and T2, it is supposed to take up to 2 different data types and then print them to the terminal using the method display()

pair.h

#ifndef PAIR_H
#define PAIR_H

template <class T1, class T2>
class Pair
{
public:
    Pair();
    Pair(const T1 & t1, const T2 & t2) : first(t1), second(t2) {}
    ~Pair();

    T1 getFirst() const {return first;}
    T2 getSecond() const {return second;}
    void setFirst(const T1 & t1) {this->first = t1;}
    void setSecond(const T2 & t2) {this->second = t2;}
    void display()
    {
        std::cout << first << " - " << second << endl;
    }


private:
    T1 first;
    T2 second;
};

#endif // PAIR_H

The class is defined on the header file "pair.h" with no .cpp file. When I attempt to create a new Object of the Pair class i get the error:

Undefined reference to 'Pair<string, string>::Pair()'
Undefined reference to 'Pair<int, int>::Pair()'
Undefined reference to 'Pair<string, int>::Pair()'
Undefined reference to 'Pair<string, string>::~Pair()'
Undefined reference to 'Pair<int, int>::~Pair()'
Undefined reference to 'Pair<string, int>::~Pair()'

When I call the default constructor of the class I call it on the main() function like

main.cpp

#include <iostream>
#include <string>
using namespace std;

#include "pair.h"

int main()
{
...
    Pair<string, string> fullName;
    fullName.setFirst(first);
    fullName.setSecond(last);
    fullName.display();
    ...
    Pair<int, int> numbers;
    numbers.setFirst(num1);
    numbers.setSecond(num2);
    numbers.display();
    ...
    Pair<string, int> grade;
    grade.setFirst(name);
    grade.setSecond(score);
    grade.display();
...
}

The makefile:

a.out : check11b.cpp pair.h
    g++ check11b.cpp

Since this is for an assignment for school, the only rules are that the makefile and the main.cpp file cannot be changed. Any help please?

Adrian Lopez
  • 51
  • 1
  • 7
  • 1
    @MajidAbdolshah that's completely wrong, you do not require a separate ".cpp" file if your header file contains all implementations. And templates have to be fully implemented in the header file, you cannot move the implementation to a separate file – UnholySheep Jul 18 '17 at 06:40
  • @UnholySheep Sure, you are right. I saw this: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Majid Abdolshah Jul 18 '17 at 06:45

1 Answers1

3

I had such error messages and all i needed to do was just to change the definition of default constructor and destructor because there is just a definition and has no actually implementation. Change the default constructor to this one.

Pair() {}

Same for the destructor.