I have a bunch of extremely similar matrix classes with only difference in their size.
For example:
class clrMatrix8x8
{
public:
clrMatrix8x8();
clrMatrix8x8(const clrMatrix8x8&);
~clrMatrix8x8();
void fill(int);
static clrMatrix8x8 elemAdd(const clrMatrix8x8&, const clrMatrix8x8&);
static clrMatrix8x8 elemSubstr(const clrMatrix8x8&, const clrMatrix8x8&);
static clrMatrix8x8 elemMult(const clrMatrix8x8&, const clrMatrix8x8&);
static clrMatrix8x8 scalMult(const clrMatrix8x8&, int);
static clrMatrix8x8 elemDiv(const clrMatrix8x8&, const clrMatrix8x8&);
static clrMatrix8x8 scalDiv(const clrMatrix8x8&, int);
int& operator()(size_t, size_t);
clrMatrix8x8& operator=(const clrMatrix8x8&);
private:
std::array<std::array<int, 8>, 8> content;
};
There are classes for 16x16, 32x32 and so on. All of them work the same as well as their functions. For clrMatrix8x8
, elemAdd
function is:
clrMatrix8x8 clrMatrix8x8::elemAdd(const clrMatrix8x8& first_, const clrMatrix8x8& second_)
{
clrMatrix8x8 temp(first_);
for (size_t i = 0; i < temp.content.size(); i++)
{
std::transform(temp.content[i].begin(), temp.content[i].end(), second_.content[i].begin(),
temp.content[i].begin(), std::plus<int>());
}
return temp;
}
The only difference between this function and the same function for other matrix is class names.
Since it doesn't feel good to have 5 similar implementations of each function for each class I thought it was possible to make a template function which is friend to all the matrix classes. So, I put template<class T> friend T elemAdd_text(const T&, const T&);
in Matrix.h
as well as inside 16x16 and 8x8 matrix classes declarations and
template<class T>
T elemAdd_test(const T& ad, const T& af)
{
T temp(ad);
for (size_t i = 0; i < temp.size(); i++)
{
std::transform(temp.content[i].begin(), temp.content[i].end(), af.content[i].begin(),
temp.content[i].begin(), std::plus<int>());
}
return temp;
}
in Matrix.cpp
to test this out, but when I call this function in main()
like this: some8x8matrixVariable = elemAdd_test(other8x8matrix_1, other8x8matrix_2);
it gets LNK2001 "unresolved external symbol" error. What am I doing wrong?
I know it would be much easier to just use a vector
of vector
s, I tested that and array
-based matrix worked ~6 times faster, and I need as much performance as possible.