Calling functions of a templated class.

Hi,

I'm working on a bit of code that performs stuff on matrices. I wanted the actual data to be flexible, so I made it a template.

1
2
3
4
5
6
7
8
9
// In Matrix.h
#include <vector>

template<typename T>
struct Matrix {
	size_t n;
	std::vector<T> data;
	std::vector<size_t> Solve();
};


I left out constructors etc for brevity. The actual numbers (data) are where the genericness comes in; the actual work in Solve() is the same for all data types.

Solve is implemented in "Solver.cpp":

1
2
3
4
5
6
7
// In Solver.cpp
#include "Matrix.h"

template <typename T>
std::vector<size_t> Matrix<T>::Solve() {
	// Do stuff here
}


In my main I make a Matrix, fill it, and try to call this function;

1
2
3
4
5
6
7
8
9
10
11
#include "Matrix.h"

int main() {
	Matrix<int> mat(4);
	// Manually fill values here

	std::vector<size_t> solution;
	solution = mat.Solve();

	return 0;
}


It compiles, but throws a linker error:
1>test.obj : error LNK2019: unresolved external symbol "public: class std::vector<unsigned int,class std::allocator<unsigned int> > __thiscall Matrix<int>::SolveMatching(void)" (?Solve@?$Matrix@H@@QAE?AV?$vector@IV?$allocator@I@std@@@std@@XZ) referenced in function _main

In the test code I've excluded all other files, so no includes or function calls beyond the ones shown. The code in Solve() calls nothing except a short-hand function for accessing elements in the data vector.

Any help?
Templates are a bit special. The implementation has to be available at the time you use the template so you more or less has to put the implementation of Solve() inside the header file. You don't necessary have to put it inside the class body, you can put it outside and you will not get multiple definition errors like you would with normal functions.
Ah, that fixed it. Thanks, man!
Topic archived. No new replies allowed.