-2

Doing my homework, got stuck on the template function part. I have the following main() in my .cpp file:

int main() 
{
Pair<char> letters('a', 'd');
cout << "\nThe first letter is: " << letters.getFirst();
cout << "\nThe second letter is: " << letters.getSecond();

cout << endl;

system("pause");
return 0;
}

I need to use template to make the class exchageable, and here is what I have in the .h file:

template <class T>
class Pair
{
private:    
  T letters;
public:
  T getFirst();
  T getSecond();
};

now, in my VS, it says both getFrist() and getSecond() are not found. How am I supposed to pass T as a class in template?

7537247
  • 303
  • 5
  • 19

1 Answers1

4

you don't have an implementation on Pair<T>::getFirst / getSecond in your .h file, do you? That's a common pitfall; your compiler needs to "see" what Pair<char>::getFirst() actually is at compile time.

When you've got the object together, and link the individual compilation units together, it's already too late.

Hence, put the implementation of your template methods in your header.

Also, don't re-invent the wheel. A char letters[2] is just as useful as your pair, and if you actually need key/value pairs, std::pair is what you want – it's even the core of associative containers like std::map.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94