0

I'm trying to learn how to use templated classes. I've created a simple templated class numbers that holds 2 numbers that can be any data type. Then I made a method that returns the bigger number of the two in the object. For some reason I keep getting linker errors though... Here's the errors and code. Not sure what's wrong, Visual Studio didn't underline anything in my code.

unresolved external symbol

They say "unresolved external symbol" if it's too small to read.

templated.h

template <class T>
class numbers {
public:
  numbers(T x, T y);
  T bigger();
private:
  T a, b;
};

templated.cpp

#include "templated.h"
#include <iostream>
using namespace std;

template <class T>
numbers<T>::numbers(T x, T y) {
    a = x;
    b = y;
}

template <class T>
T numbers<T>::bigger() {
    return a > b ? a : b;
}

main.cpp

#include <iostream>
#include "templated.h"
using namespace std;

int main() {

    numbers <int>pair(1, 2);
    cout << pair.bigger() << endl;

    return 0;
}

Thanks for reading!

Matt Corby
  • 11,984
  • 3
  • 12
  • 19

1 Answers1

5

You're not supposed to put template implementations in a cpp/c file. Move them all to your .h file.

This is because cpp files are supposed to take functions that compile into implementation libraries (like dll files or compiled objects), while template functions have undefined types (yet), whose types get defined at compile time.

You can, however, put specializations of your template functions in the cpp file, where you specify what types you want to include in your compiled objects.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189