0

Is there a way I can overload the "/" operator for a boost vector in C++?

#include <boost/assign.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/operations.hpp>
#include <boost/numeric/ublas/assignment.hpp>

namespace ublas = boost::numeric::ublas;


using namespace boost::assign;

template <typename T, typename U>
ublas::vector<T> operator/(U& var)
{
// do something here
return *this;
}

I am seeing errors like Overloaded 'operator/' must be a binary operator (has 1 parameter)

Pat
  • 627
  • 1
  • 9
  • 24

2 Answers2

2

What you need is this:

#include <boost/assign.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/operations.hpp>
#include <boost/numeric/ublas/assignment.hpp>

namespace ublas = boost::numeric::ublas;
using namespace boost::assign;

template <typename T, typename U>
ublas::vector<T> operator/(ublas::vector<T> v, U& var)
{
    // your logic for /
    return v;
}


int main()
{
    ublas::vector<int> v1;
    auto v2 = v1 / 2;
    return 0;
}
Sarang
  • 1,867
  • 1
  • 16
  • 31
  • Thanks Sarang, I was able to get it working. I have another question. I tried copying the operator definition into a header file and calling the header. It doesn't quite work. How can I organize this such all the operator overloads can be in a header and I just include it in my project? `code' template ublas::vector operator/(ublas::vector v, U& var) { // your logic for / return v; }`code` – Pat Nov 10 '12 at 01:49
  • Update: I got it working. I had to dump the code in the header and not define the operator overload in the header and the rest of the code in the cpp. So just take the overload and dump it straight into the header. I don't know why this works? – Pat Nov 10 '12 at 02:02
1

The operator function you have is a stand-alone function, not a member of a class, so it needs two arguments of the objects it should work upon, and as it's not a class member it has no this either.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621