Many questions seem similar but I didn’t find a precise answer.
Here is a pseudo-code snippet to illustrate the question:
T1 lhs;
T2 rhs;
T3 res;
decltype(lhs+rhs) res2;
// Ti are all standard arithmetic types
res = lhs+rhs;
res2;
This page about arithmetic operators describes how lhs and rhs are converted to rvalue with possibly new types (the conversion is described in usual arithmetic conversions) but I cannot find the rule regarding the return type of the expression lhs+rhs
and of decltype(lhs+rhs)
if they are the same (which I expected).
The page about expressions tells that they have a type but I could not find the rules for this type.
If I believe the array at the beginning of arithmetic operators, it should be the type of lhs
after conversion but I’m finding a different result:
#include <type_traits>
int main() {
signed char lhs;
char rhs;
// static_assert(std::is_same_v<signed char, decltype(lhs + rhs)>);
static_assert(std::is_same_v<int, decltype(lhs + rhs)>);
auto res = lhs+rhs;
// static_assert(std::is_same_v<signed char, decltype(res)>);
static_assert(std::is_same_v<int, decltype(res)>);
static_assert(std::is_same_v<decltype(lhs + rhs), decltype(res)>);
}
LIVE
My understanding is that, as both operand are of the same type, they don’t undergo any conversion and the return type should be also signed char
but as the demo shows, decltype
yields int
.
NB the page about operator overloading, Binary arithmetic operators section also suggest that the return type should be the same as the (common) arguments one.
To sum it up:
1- Is it correct that, when a binary (arithmetic) operator is called on two operands, if they are of different types, they undergo some conversion to a common type (rules given above, in cppreference)?
2- What if the type of x op y
when x
and y
are of the same arithmetic type T
?
3- Is it the same as decltype
(I think so)?