I recently learned about c++ templates and was testing them out with a matrix class:
template<typename T>
class Matrix
{
public:
Matrix();
int width;
int height;
Matrix operator*(const Matrix& rMatrix)
Matrix operaor+(const Matrix& rMatrix)
// other matrix operations/functions here
private:
T* data;
};
I then found that templates could take non-type parameters, allowing me to do this:
template<typename T, int width, int height>
class Matrix
{
public:
Matrix();
template <int width2>
Matrix<T, width2, height> operator*(const Matrix<width2, width>7 rMatrix)
// other matrix operations/functions here
private:
T* data;
};
I figured that the latter was probably better if you knew all the sizes you would need at compile-time, as it would generate compilation errors if the matrices were the wrong size (for the multiplication/addition operations), whereas the former forced me to check this at run-time. I was, however, worried that the compiler would be generating different functions for adding a 4x4 to a 4x4 vs a 3x3 to a 3x3 (assuming both had the same type), which would be inefficient.
So my question is this: will the compiler I'm using (g++) generate multiple functions from a template when there is a variation in a non-type parameter (in the above example, matrix width/height)?
edit/clarifications:
- the functions are not defined inline (they are in a separate .tpp file)
- by 'inefficient', I mean that (by my understanding) having these variations on the function will cause the compiled executable to be larger than it would otherwise be