The type of return depending on the order in the arithmetic operation. Is it correct?

Consider the following code snippet:

template <typename U>
struct Un {
    Un (int p) : n {p} {}

    U operator+ (U v) const {
        return U {n + v.n};
    }

    int n {};
};

struct R : Un<R> {
    using Un::Un;
};

struct D : Un<D> {
    using Un::Un;
    D (R v) : Un {v.n} {}
    operator R () const {
        return n;
    }
};

and the following is used:

template <typename T>
void what_type (T t) {
    std::cout << "type R = " << std::is_same<T, R>::value << std::endl;
    std::cout << "type D = " << std::is_same<T, D>::value << std::endl;
}

R r {10};
D d {10};

what_type (r+d);
what_type (d+r);

:

type R = 1
type D = 0
type R = 0
type D = 1

which means that if in an arithmetic expression the type Roccurs as the first, the whole expression has a type R, and if the type Doccurs first, then the expression has a type D.

So my understanding is this:

at r+dfirst we create the type of object R, then the object type Dand, as Dis operator R(), the object Dis converted to Rthat fact gives us r+r.

in d+r D, R , D , R, D R, d+d.

? ?

+4
2

. operator+ -. , . D R it D R .

d+r , d.operator+(r), Un<D> D. r+d.

. .

+6

. ?

, . .

.

, :

struct A { operator int() const; };
struct B { operator int() const; };

A operator+(A, int);
B operator+(B, int);

A a;
B b;

a + b // resolved as a + (int)b; the type of the expression is A
b + a // resolved as b + (int)a; the type of the expression is B

, B operator+(B, int); , b + a , (int)a + (int)b, int.

+1

Source: https://habr.com/ru/post/1659026/


All Articles