Skip to main content
gamedev.net
🔒 Locked

Passing Fundamental operator pointers

Started by timgradwell 4 replies 750+ views
Original Post
timgradwell
timgradwell
Hi, I'm writing a matrix class for practice purposes. Can I pass fundamental type operators such as +=, -=, *= as parameters? Can I do this? (have one function that applies the relevant operator to all the members)

class Moo
{
   private:
      int x;
      int y;
      int z;
      int w;
      // ...

      Moo& assignAndOperate(int&,int&(*)(int&));

   public:
      Moo& operator+=(int& i) { return assignAndOperate(i, +=); }
      Moo& operator-=(int& i) { return assignAndOperate(i, -=); }
      Moo& operator*=(int& i) { return assignAndOperate(i, *=); }
      Moo& operator/=(int& i) { return assignAndOperate(i, /=); }
      

};

Moo& Moo::assignAndOperate(int& i,int&(*oper)(int&))
{
   oper(x,i);
   oper(y,i);
   oper(z,i);
   oper(w,i);
   // ...

   return *this;
}



or do I have to do this? (define each operator to be applied to each member)

class Moo
{
   private:
      int x;
      int y;
      int z;
      int w;
      // ...


   public:
      Moo& operator+=(int& i);
      Moo& operator-=(int& i);
      Moo& operator*=(int& i);
      Moo& operator/=(int& i);
      

};

Moo& Moo::operator+=(int& i)
{
   x+=i;
   y+=i;
   z+=i;
   w+=i;
   // ...
   return *this;
}

Moo& Moo::operator-=(int& i)
{
   x-=i;
   y-=i;
   z-=i;
   w-=i;
   // ...
   return *this;
}

Moo& Moo::operator*=(int& i)
{
   x*=i;
   y*=i;
   z*=i;
   w*=i;
   // ...
   return *this;
}

Moo& Moo::operator/=(int& i)
{
   x/=i;
   y/=i;
   z/=i;
   w/=i;
   // ...
   return *this;
}


Cheers.
ToohrVyk
ToohrVyk
+= corresponds to the function T& operator+=(T&,const T&). Use the name operator +=.

EDIT: darn, I missed the fact that you were manipulating basic types. My statement applies to class operators only.



[Edited by - ToohrVyk on December 28, 2006 2:17:47 PM]
Anon Mike
Anon Mike
You can't do it directly like that no. The usual trick is to use a functor instead. e.g. see std::plus, std::minus, etc.
-Mike
Zahlman
Zahlman
I hope 'Moo' isn't a vector class. The operation (scalar + vector) doesn't make any sense, and transforming the scalar into a vector with every element matching the scalar certainly isn't the way to make it make sense.
timgradwell
timgradwell
Quote:
Original post by Zahlman
I hope 'Moo' isn't a vector class.


Nope. Trivial example to help explain my "operator" question.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.