Reputation: 1329
I read this post to get an overview of the type and value category returned from the conditional operator: Return type of '?:' (ternary conditional operator)
That answers pretty much my question, except the phrasing in C++ Primer to describe the same thing confuses me slightly.
"That result of the conditional operator is an lvalue if both expressions are lvalues or if they convert to a common lvalue type. Otherwise the result is an rvalue."
The bolded bit throws me off. This would suggest to me that, for instance
int main(){
int y = 2;
char z = 3;
((50<60) ? y : z) = 3;
}
would be fine, because y and z can be both converted to int (well, z would be the one converted) which is an lvalue type (right?), thus the conditional operator would give an lvalue as its value category. This codedoes not compile however, because it actually gives out an rvalue. Can anyone provide an example of the exceptional case mentioned by the bolded bit, so I can understand what point it's trying to make?
My understanding seems to be that: If the expression are lvalues of the same type, then an lvalue of that type is returned. Otherwise an rvalue (of some compiler-determined type) is returned.
Upvotes: 3
Views: 89
Reputation:
If z
is converted to int
, the lvalue-to-rvalue conversion has already been applied, and the result is a prvalue, not an lvalue.
One example of ?:
where the two operands have different types, but the result is an lvalue, is when one is const
-qualified and the other isn't:
const int &f(bool a, int &b, const int &c) {
// b has type int, c has type const int, the result is an lvalue of type const int
return a ? b : c;
}
Another example is where one is a class with a custom conversion operator:
struct S {
operator int&();
};
int &f(bool a, int &b, S &c) {
// b has type int, c has type S, the result is an lvalue of type int
// if a is false, c's conversion operator is called
return a ? b : c;
}
Upvotes: 3