Re: Non-member operator overloading, linker complains
Michael Hofmann <mhofmann79@arcor.de> writes:
#include <iostream>
#include <algorithm>
#include <vector>
template<typename T, unsigned int d, unsigned int e> class Matrix
{
private:
friend Matrix<T, d, e> operator-( const Matrix<T, d, e>& m );
This declares a non-template.
typedef std::vector<T> data_type;
data_type data_;
public:
Matrix( T value )
{
data_.resize( d * e );
std::fill( data_.begin(), data_.end(), value );
}
// ...
};
template<typename T, unsigned int d, unsigned int e> class Matrix;
template<typename T, unsigned int d, unsigned int e>
Matrix<T, d, e> operator-( const Matrix<T, d, e>& m );
template<typename T, unsigned int d, unsigned int e> class Matrix
{
friend Matrix<T, d, e> operator- <>( const Matrix<T, d, e>& m );
etc.
should help.
template <typename T, unsigned int d, unsigned int e>
Matrix<T, d, e> operator-( const Matrix<T, d, e>& m )
This defines a template.
{
Matrix<T, d, e> mRes( m );
Matrix<T, d, e>::data_type::iterator itrEnd = mRes.data_.end();
for ( Matrix<T, d, e>::data_type::iterator itr =
mRes.data_.begin(); itr != itrEnd; ++itr )
(*itr) = -(*itr);
return mRes;
}
template <typename T, unsigned int d, unsigned int e, unsigned int f>
Matrix<T, d, f> operator*( const Matrix<T, d, e>& m1,
const Matrix<T, e, f>& m2 )
{
// does multiplication without accessing
// private members of Matrix<>
// ...
return Matrix<T, d, f>( 0.0 ); // dummy return
}
int main()
{
Matrix<double, 3, 3> m( 1.0 );
Matrix<double, 3, 3> n( 2.0 );
Matrix<double, 3, 3> o = m * n; // no problems
Non non-template to be referenced here, so the template specialization
is referenced.
Matrix<double, 3, 3> p = -n; // yields linker error
This references the non-template, which hasn't yet be defined.
return ( EXIT_SUCCESS );
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]