Tom de Geus
Tom de Geus

Reputation: 5975

Partial template specialization to unroll loops for specific sizes

I have written a matrix class which can take different sizes. Now I want to unroll loops for specific sizes. How should I do this?

The only way I can seem to get working is a child-class for 2-d. But this I would like to avoid, as it would result in much duplicate code.

For example:

#include <iostream>

template<class T, size_t M, size_t N>
class matrix
{
  matrix<T,M,N>& operator*= (const matrix<T,M,N> &B);
};

template<class T, size_t M, size_t N>
matrix<T,M,N>& matrix<T,M,N>::operator*= (const matrix<T,M,N> &B)
{
  // ...
  return *this;
}

int main()
{
  return 0;
}

Now I would like to add an implementation for the case that M = 2 and N = 2 where I unroll all loops to gain efficiency.

(I have timed the unroll in a previous implemenation, and it really does seem to make sense, in particular for more complicated operations then featured in this example.)

Upvotes: 2

Views: 70

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136495

You can delegate operator*= to an overloaded function template. E.g.:

template<class T, size_t M, size_t N>
class matrix
{
public:
    matrix<T,M,N>& operator*=(const matrix<T,M,N>&);
};

// Generic version.
template<class T, size_t M, size_t N>
void inplace_dot(matrix<T,M,N>& a, matrix<T,M,N> const& b); 

// Overload for 2x2 matrix.
template<class T>
void inplace_dot(matrix<T,2,2>& a, matrix<T,2,2> const& b);

template<class T, size_t M, size_t N>
matrix<T,M,N>& matrix<T,M,N>::operator*=(const matrix<T,M,N>& b)
{
    inplace_dot(*this, b);
    return *this;
}

Upvotes: 4

Related Questions