Why does the is_assignable_v<int, int>
and is_assignable_v<int&, int>
have different result? is_assignable_v<int&, int>
returns true but is_assignable_v<int, int>
returns false. It's not very intuitive.
is_assignable_v
is std::declval<T>() = std::declval<U>()
by definition from cppreference.com.
That means, std:declval<int>() = std::declval<int>()
return false but std:declval<int&>() = std::declval<int>()
returns true.
std::declval<int>()
is rvalue of int. Then what does std::declval<int&>()
mean? If it means reference to rvalue int, then Is is possible reference to int without const can refer rvalue?
I totally confused about is_assignable_v
.
Could you explain it for me?
std::declval<int>()
is rvalue ofint
. Then what doesstd::declval<int&>()
mean?
Lvalue int
, due to reference collapsing.
For scalar types, you can only assign to lvalues, not rvalues. For classes, you can by default assign to rvalues too, unless you intentionally prevent that.
Note that references can't be retargeted by assigning to them, instead this assigns to whatever the reference points to.
Also note that expressions can't have reference types, so trying to assign to a "reference to int
" is no different from trying to assign to lvalue (or rvalue) int
.