This question came up during my study of decltype
behavior and its rules in deriving the type of expressions. Is there any reason not to promote common cv-qualifiers if an expression is of prvalue?
type. Ex:- in the below code the expression i+j
is just derived by
decltype
as int
rather than const int
, since const
ness is common across both variables it could be propagated to the resulting expression as well, although the expression itself is temporary and is not lvalue but when it comes to type derivation it may be useful (as is the case with single value expressions).
Existing rule : If the value category of expression is prvalue, then decltype
yields T
.
#include<iostream>
#include<string>
#include<type_traits>
using namespace std;
int main(int argc, char* argv[])
{
const int i=10;
const int j=20;
cout << is_same<decltype(i), const int>::value << "," << is_same<decltype(j), const int>::value << endl;
cout << is_same<decltype(i+j), const int>::value << "," << is_same<decltype(i+j), int>::value << endl;
return(0);
}
As per the CPP standard draft n4713:
8.2.1 Value category [basic.lval]
...
9. ... Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types.
Since (i + j)
evaluates to a non-class prvalue, it will have a cv-unqualified type and using decltype
on it yields an int
.