2

The question is if I can find a way to make a parametrized overloading of an operator i.e. instead of

template <class T>
class A
{
   private:
       T m_var;
   public:
       operator T () const { return m_var; }
       const A operator+ ( const A& r_var ) const { return m_var + r_var; }
       const A operator- ( const A& r_var ) const { return m_var - r_var; }
       const A operator* ( const A& r_var ) const { return m_var * r_var; }
       const A operator/ ( const A& r_var ) const { return m_var / r_var; }
   ...........
}

to have something like this

template <class T>
class A
{
   private:
       T m_var;
   public:
       operator T () const { return m_var; }
       const A operator 'X' ( const A& r_var ) const { return m_var 'X' r_var; }

   ...........
}

where 'X' will take values +, -, *, /, and in this way to avoid repetition of the same pattern code. Thanks in advance.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
meta-cpp
  • 61
  • 2

2 Answers2

2

Check out boost::operators. It requires += and *= to be defined by you. The rest(+,-,*,/,-=,/=) are defined by the library. It also works for binary operators.

rymurr
  • 444
  • 4
  • 11
0

This isn't possible within templates. You will need to write a macro.

Also, you should not return a const rvalue, because it's perfectly legal to call non-const methods on rvalues of class type.

Puppy
  • 144,682
  • 38
  • 256
  • 465