user922475
user922475

Reputation:

C++ custom compile-time check

Let's say I have two Matrice classes. One matrix is 2 by 2, the other 3 by 3 and then I go to multiply them together. Of course I cannot multiply two matrices that don't have the same dimensions.

I am aware that I can build in a run-time check, but is there a way to build in a compile-time check using the c++ language? So if I try to compile a program where two defined matrices of different dimensions are multiplied it will through a compile-time error.

Matrix *matrix1 = new Matrix(2,2);
Matrix *matrix2 = new Matrix(3,3);

Matrix_Multiply(matrix1,matrix2);  // compiler throws error on this line 

Also while we are on this topic, are there any programming languages that have this feature?

Upvotes: 0

Views: 227

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

You can define a template matrix class with dimensions as template parameters. When you define an operator*() for this type only, the compiler will prevent multiplication of this type with another.

template<int rows, int cols> class matrix {
public:
    friend matrix operator*(const matrix &m1, const matrix &m2);
};

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153830

The answer depends on how your matrices get a dimension: If the dimensions are determined at run-time, there is no compile-time check. However, if the matrices are compile-time dimensioned, I'd think that you'll naturally end up having compile time checks:

template <typename T, int Width, int Height>
class Matrix;

template <typename T, int M, int N, int O>
Matrix<T, M, O> operator* (Matrix<T, M, N> const& lhs, Matrix<T, N, O> const& rhs);

That is, the size of the result matrix is deduced by the sizes of the two argument matrices. If they have mismatching dimensions, no suitable multiplication operator would be found.

Upvotes: 1

Related Questions