Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No class subtraction operator overloaded but still works

Tags:

c++

I have this piece of code:

#include <iostream>
using namespace std;

template <typename T1, typename T2>
class Number {
    T1 value;
public:
    Number(const T1& val): value(val){};
    operator T2() { return (T2)(value / 2); }
    T1 operator+(const T1& val) { return value + val; }
};

int main() {
    Number<int, float>n1(10);
    Number<float, int>n2(3.0);
    cout << n1 + n2 << ", " << n2 + n1 << ", " << n1 - n2 << endl;
}

In spite having no subtraction operator overloaded this code still works and outputs: 11, 8, 4.

Shouldn't it throw an error at compile time ?

Any idea will be appreciated.

like image 910
Alex C Avatar asked Nov 23 '25 13:11

Alex C


1 Answers

When the compiler sees n1 - n2, it performs an overload resolution. For any pair of promoted arithmetic types L and R, the following signatures participate in overload resolution:

LR operator-(L, R)

where LR is the result of usual arithmetic conversions on L and R. (See cppreference) No other signature that participates in overload resolution is relevant.

Therefore, n1 is converted to 5.0f with the help of operator T2(), and n2 is similarly converted to 1. And 5.0f - 1 is 4.0f.

like image 112
L. F. Avatar answered Nov 26 '25 02:11

L. F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!