Non-null objects, the Null Object pattern, and T.init

Michel Fortin michel.fortin at michelf.ca
Sat Jan 18 14:16:24 PST 2014


On 2014-01-18 21:57:21 +0000, Walter Bright <newshound2 at digitalmars.com> said:

> On 1/18/2014 1:38 PM, Michel Fortin wrote:
>> The closest thing I can think of is range constrains. Here's an example
>> (invented syntax):
> 
> I don't think a new syntax is required. We already have the template syntax:
> 
>     RangedInt!(0,10)
> 
> should do it.

It works, up to a point.

	void foo(RangedInt!(0, 5) a);

	void bar(RangedInt!(0, 10) a)
	{
		if (a < 5)
			foo(a); // what happens here?
	}

In that "foo(a)" line, depending on the implementation of RangedInt you 
either get a compile-time error that RangedInt!(0, 10) can't be 
implicitly converted to RangedInt!(0, 5) and have to explicitly convert 
it, or you get implicit conversion with a runtime check that throws.

Just like pointers, not knowing about the actual control flow pushes 
range constrains enforcement at runtime in situations like this one. 
It's better than nothing since it'll throw immediately when passing an 
out of range value to a function  and thus the wrong value won't 
propagate further, but static analysis would make this much better.

In fact, even the most obvious case can't be caught at compile-time 
with the template approach:

	void baz()
	{
		foo(999); // runtime error here
	}

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list