'Is there an equivalent of Python's __rmul__ in C++?
Python 3 allows overloading of *.
For example,
a*b
Allows a to define the result by providing a __mul__ method.
If however that method returns NotImplemented, the __rmul__ method on b is called (if it exists) to give the result. This is documented here.
One advantage of this is that I can make on object b that operates on a without knowing the class of a.
Is there an equivalent to __rmul__ in C++, or a way of achieving the same or a similar thing?
Solution 1:[1]
Correct me if I'm wrong, but according to my understanding, you need to overload an operator for 2 different classes.
You can do something like this as under:
#include <iostream>
class A
{
public:
int integer;
};
class B
{
public:
double decimal;
};
//A * B
double operator*(A a, B b)
{
return a.integer * b.decimal;
}
int main()
{
A a{12}; B b{2};
double c = a * b;
std::cout << c;
}
In the above example, I've overloaded operator* to multiply 2 objects of type A and B. But it only works for a * b, not b * a. So you can do something like this:
//B * A
double operator*(B b, A a)
{
return a.integer * b.decimal;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
