|
|
|
|
|
by benbataille
4800 days ago
|
|
If it was that simple, people wouldn't have any issue with the conditional operator. The problem is there actually is a semantic difference between the two lines you wrote in most languages. If-Then-Else is a statement. It doesn't return a value. It's just a branching operation between the two blocks. The conditional operator is an expression. It returns a value hence it has a type. And that's where things start to be messy. Typing rules for the conditional operator are, well, not trivial and varie from language to language. Let's use an exemple from Java Puzzlers (Joshua Bloch and Neal Gafter) : char x = 'X';
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x); will print X88 but the same thing in C++ char x = 'X';
int i = 0;
cout << (true ? x : 0);
cout << (false ? i : x);
will print 8888.And I am not even talking about the priority mess when you try to use a conditional operator in a conditional operator. |
|
You could expose the same semantic difference your example relies on with overload resolution, without needing to refer to the ternary operator at all. But I hope you wouldn't take that to mean that overloads are also a bad idea.
I also believe that the ternary operator is particularly nice when used in combination:
The idiom tastes a little like pattern matching. Of course, you need to be a little cautious about your precedence, but I've never used a language supporting infix operators that didn't have gotchas around precedence.