Name: Anonymous 2009-04-15 10:02
Hi /prog/
A nice question for you. I'd like to study C++ templates, and I've found something that sound strange. This is my simple code, it implements a matrix class:
Header file (matrix.h)
Implementation file (matrix.cpp)
[b]Main (main.cpp)[b]
If I try compiling this stuff the compiler works well, but there's a linker error such
Althrough this approach stinks, I've tried to include the '.cpp' file into main.cpp instead of including the '.h' file, and it works.
Can you explain me what's going on?
A nice question for you. I'd like to study C++ templates, and I've found something that sound strange. This is my simple code, it implements a matrix class:
Header file (matrix.h)
#ifndef __MATRIX_H__
#define __MATRIX_H__
template <typename T>
class Matrix {
private:
T **matrix;
unsigned nrows;
unsigned ncols;
public:
Matrix(unsigned nrows, unsigned ncols);
};
#endif /* __MATRIX_H__ */Implementation file (matrix.cpp)
#include "matrix.h"
template <typename T>
Matrix<T>::Matrix(unsigned nrows, unsigned ncols)
{
int i;
matrix = new T* [ncols];
for (i=0; i<ncols; i++)
matrix[i] = new T;
}[b]Main (main.cpp)[b]
#include <iostream>
using namespace std;
#include "matrix.h"
int main(int argc, char **argv)
{
Matrix<int> x(10,20);
}If I try compiling this stuff the compiler works well, but there's a linker error such
/tmp/ccBo2hkV.o: In function `main':
main.cpp:(.text+0x84): undefined reference to `Matrix<int>::Matrix(unsigned int, unsigned int)'
collect2: ld returned 1 exit statusAlthrough this approach stinks, I've tried to include the '.cpp' file into main.cpp instead of including the '.h' file, and it works.
Can you explain me what's going on?