Non-null objects, the Null Object pattern, and T.init
Michel Fortin
michel.fortin at michelf.ca
Sat Jan 18 16:25:32 PST 2014
On 2014-01-18 22:28:14 +0000, Walter Bright <newshound2 at digitalmars.com> said:
> On 1/18/2014 2:16 PM, Michel Fortin wrote:
>> 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.
>
> Yes, and I'm not seeing the problem. (The runtime check may also be
> removed by the optimizer.)
I'm not concerned about performance, but about catching bugs early. You
said it: the compiler (the optimizer) knows (more or less) whether it
is possible for you to have an error here (which is why the check might
disappear as dead code), but it will let it pass and make the generated
code wait until a bad value is passed at runtime to throw something.
Couldn't we tell the compiler to emit an error if a function argument
"might" be in the offending range instead? That'd be much more useful
to find bugs, because you'd find them at compile-time.
>> Just like pointers, not knowing about the actual control flow pushes range
>> constrains enforcement at runtime in situations like this one.
>
> With pointers, the enforcement only happens when converting a pointer
> to a nonnull pointer.
True.
>> 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
>> }
>
> Sure it can. Inlining, etc., and appropriate use of compile time constraints.
Inlining will not allow the error to be caught at compile time,
although it might allow the runtime check to be eliminated as dead
code. But this is not about performance, it's about detecting this kind
of bug early (at compile time).
--
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca
More information about the Digitalmars-d
mailing list