I have a matrix class that supports operations with scalar values that I implemented using operator overloading. Since each overloaded operator function has the same body except for the operator being used, I decided to create a generic function that would accept a function along with the matrix and a scalar value to consolidate my code.
Here is the generic function and it being called from the overloaded addition operator function:
// Generic function to take care of matrix operations
template<typename T, typename F>
Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f) {
std::vector<std::vector<T> > new_els = a.elements;
typename std::vector<std::vector<T> >::iterator it = new_els.begin();
typename std::vector<T>::iterator it_in;
for (; it != new_els.end(); ++it) {
it_in = it->begin();
for (; it_in != it->end(); ++it_in) {
*it_in = f(*it_in, b);
}
}
return Matrix<T>(new_els);
}
// Add scalar to all values in Matrix
template<typename T>
Matrix<T> operator+(const Matrix<T> &a, const T b) {
return scalar_operation(a, b, std::plus<T>());
}
And here are the functions declared in the matrix class:
template<class T>
class Matrix {
template<typename F>
friend Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f);
friend Matrix<T> operator+<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator-<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator*<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator/<>(const Matrix<T> &a, const T b);
When I implemented the overloaded operator functions separately, they worked, but with this implementation, I get the following compiler error:
Undefined symbols for architecture x86_64:
"Matrix<float> scalar_operation<std::__1::plus<float> >(Matrix<float> const&, float, std::__1::plus<float>)", referenced from:
Matrix<float> operator+<float>(Matrix<float> const&, float) in matrix_test-3188cd.o
ld: symbol(s) not found for architecture x86_64
I imagine my error is related to the Matrix<float> scalar_operation<std::__1::plus<float> >(
line because it looks like the linker is searching for a function with this header, which is slightly different from how it's declared in my file, but I've tried modifying my declaration and it throws additional errors.
Why am I getting this error and how can I fix it? Thanks!
EDIT: To clear up some confusion, all the code has been implemented in the header file since it is a templated class. There is no corresponding .cpp file.