www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Auto-casting the subexpressions of a ternary operator to the expected

reply Larry Hastings <larry hastings.org> writes:
This isn't a *bug*, per se, but an area where I think D (and many other 
C-like languages) could arguably be improved.

The ternary operator doesn't like having objects of different types for 
the if and else subexpressions.  Since the compiler already knows the 
ultimate type for the expression en toto, it'd be nice if it propogated 
down to the if and else subexpressions so that they could be 
auto-demoted to the proper type.

Here's what I mean:
//
class classA
	{
	int i;
	}

class classB : classA
	{
	int j;
	}

class classC : classA
	{
	int k;
	}

void polymorphic(classA a)
	{
	printf("a.i is %d\n", a.i);
	}

int main()
	{
	classB b = new classB;
	b.i = 4;
	polymorphic(b);

	classC c = new classC;
	c.i = 5;
	polymorphic(c);

	// Ternary operator with explicit casts.
	// This statement compiles and runs.
	polymorphic((b.i < c.i) ? cast(classA)b : cast(classA)c);

	// Ternary operator with implicit casts.
	// This statement won't compile.
	polymorphic((b.i < c.i) ? b : c);

	return 0;
	}
//

I think the "ternary operator with implicit casts" call should be 
equivalent to the "ternary operator with explicit casts" call.  My gut 
feeling is that this wouldn't become a source of surprises (aka bugs). 
I think the coder's intent in these cases would be clear.

p.s. Is the convention in this newsgroup for "here's some inline code" a 

been some years since I hung out in a newsgroup.

--
/larry/
Apr 16 2005
next sibling parent "Regan Heath" <regan netwin.co.nz> writes:
On Sat, 16 Apr 2005 10:01:50 -0700, Larry Hastings <larry hastings.org>  
wrote:
 p.s. Is the convention in this newsgroup for "here's some inline code" a  

 been some years since I hung out in a newsgroup.
Or | of any character you like. The intention is to preserve the indentation of code. Some readers/writers munge it. Regan
Apr 16 2005
prev sibling parent J C Calvarese <jcc7 cox.net> writes:
Larry Hastings wrote:
 
...
 p.s. Is the convention in this newsgroup for "here's some inline code" a 

 been some years since I hung out in a newsgroup.
 
 -- 
 /larry/
I think the convention was mostly designed for people posting from the web interface (which has a nasty habit of deleting leading spaces). Since you're posting from a newreader that doesn't chop off leading spaces, I'd just keep on doing what you're doing. Obviously, void main() { printf("hello world"); } is code. void main() { printf("hello world"); } is clearly code, too, but it's not as easy to read (especially when several blocks get nested). -- jcc7 http://jcc_7.tripod.com/d/
Apr 16 2005