How do I pass vectors in a class template?

Hello,
I'm trying to write a Matrix class using two dimensional vectors. Everything works fine until I try to create a class template.

The idea is that the user would enter all the matrix data into a one dimensional vector. This vector, along with the matrix row and column dimensions, would be passed as arguments to the constructor.

The .h and .cpp files compile OK as long as I don't actually try to create a Matrix object. Then I get this error:

main.cpp:(.text+0xc4): undefined reference to `Matrix<std::vector<int, std::allocator<int> > >::Matrix(unsigned int, unsigned int, std::vector<int, std::allocator<int> > const&)'


Here is the header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Header file for the matrix class

#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template <class T>
class Matrix {
	public:
		Matrix(unsigned rows, unsigned cols, const T& v);
	private:
		vector<T> data_;
		void addData(const T& v);
		size_t nRows;
		size_t nCols;
};
#endif 


Definitions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "matrix.h"

template <class T>
Matrix<T>::Matrix(unsigned rows, unsigned cols, const T& v) {
	data_.resize(rows);
	nRows = rows;
	nCols = cols;
	for(int i = 0; i < rows; ++i)
		data_[i].resize(cols);	
	addData(v);
}

template <class T>
void Matrix<T>::addData(const T& v) {
	int j = 0;  //counter for the one dimensional vector

	for(int i = 0; i < nRows; ++i) 
		for(int k = 0; k < nCols; ++k) {
		data_[i][k] = v[j];
		++j;
	}
}


main:
1
2
3
4
5
6
7
8
9
10
11
12
#include "matrix.h"
#include <iostream>
using namespace std;

int main() {
	vector<int> v;
	// add six ints for a 2x3 matrix
	for(int i = 0; i < 6; ++i)
		v.push_back(i);
	Matrix< vector<int> > m(2, 3, v);
	return 0;
}


I've also tried implementing it like this:

Matrix(unsigned rows, unsigned cols, const vector<T>& v);

and changing main.cpp to:

Matrix<int> m(2, 3, v);

but I get the same error message.

If anyone knows what I'm doing wrong I'd really appreciate some help.

Thanks,
gr

Template function declarations and implementations must be in the same file.
Thanks very much Helios, that was it!

gr
Topic archived. No new replies allowed.