Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ two-way operators, is it possible?

For example, we have this class:

class my_class
{
public:
  friend my_class operator* (const my_class&, int a);
  friend my_class operator* (int a, my_class&);  
};

my_class operator* (int a, my_class&)
{
    // do my_class * a
}

my_class operator* (int a, my_class&)
{
    // do a * my_class
}

is it possible to do just one operator* to do what these two do?

Thanks!

like image 609
marquesm91 Avatar asked Dec 10 '25 07:12

marquesm91


1 Answers

You cannot do that. However, you can implement one and simply call it from the other one:

my_class operator *(const my_class &l, int r) {
    // implement the actual operator here.
}

my_class operator *(int l, const my_class &r) {
    return r * l;
}

(Note that you cannot implement the latter function as part of the class. You have to do it externally. The first function can be implemented as an instance method, because its first argument is of the class type.)

like image 152
mmx Avatar answered Dec 11 '25 20:12

mmx