简体   繁体   中英

Defining Operator Overloads Outside Templated Class

When I compile the following,

#include <boost/numeric/ublas/vector.hpp>
#include <iomanip>
#include <stdio.h>

namespace ublas = boost::numeric::ublas;

template <class T> class Vector
{
    private:

       ublas::vector<T> m_ublas_vec;
       unsigned m_size;

    public:

       Vector(unsigned s){
          m_size = s;
          m_ublas_vec.resize(m_size);
       }

       T &operator () (unsigned idx) {
          if(idx >= m_size){
             perror("ERROR: Index out of bounds!\n");
             exit(1);
          }
          return m_ublas_vec(idx);
       }

       // Right-multiply by scalar.
       template <class TT, class S>
       friend Vector<TT> operator * (const Vector<TT> &, S);

       // Left multiply by scalar.
       template <class TT, class S>
       friend Vector<TT> operator * (S, const Vector<TT> &);
};

template <class T, class S>
Vector<T> Vector<T>::operator * (const Vector<T> &v_in, S scalar){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

template <class T, class S>
Vector<T> Vector<T>::operator * (S scalar, const Vector<T> &v_in){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

I get this error:

vector_test.cpp:49:95: error: invalid use of incomplete type 'class Vector'

vector_test.cpp:7:26: error: declaration of 'class Vector'

What am I doing wrong?

You friend functions don't declare member functions. So, you want to define them as

template <class T, class S>
Vector<T> operator * (const Vector<T> &v_in, S scalar){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

template <class T, class S>
Vector<T> operator * (S scalar, const Vector<T> &v_in){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

friend function is not a part of class. You should not define it via Vector<T>:: specifier. Correct one is:

template <class T, class S>
Vector<T> operator * (const Vector<T> &v_in, S scalar){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

template <class T, class S>
Vector<T> operator * (S scalar, const Vector<T> &v_in){
   Vector<T> v_out (v_in.m_size);
   v_out.m_ublas_vec = v_in.m_ublas_vec*static_cast<T>(scalar);
   return v_out;
}

Check: http://ideone.com/8n9UO1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM