endless loop with ref and non-ref parameter

Jonathan M Davis jmdavisProg at gmx.com
Thu Jan 24 11:33:57 PST 2013


On Thursday, January 24, 2013 18:24:32 Namespace wrote:
> In relation to this post:
> http://forum.dlang.org/thread/hlyospppnjiziyokfvdd@forum.dlang.org?page=2#po
> st-qxqvreqpniftjnwxvqgt:40forum.dlang.org
> 
> I dicided to test a bit with "manual" auto ref.
> This Code works as expected.
> 
> [code]
> import std.stdio;
> 
> struct A {
> public:
> 
> }
> 
> void foo(A a) {
> writeln("without ref");
> foo(a);
> }
> 
> void foo(ref A a) {
> writeln("with ref");
> }
> 
> void main() {
> foo(A());
> }
> [/code]
> 
> it prints:
> without ref
> with ref
> 
> but if I change
> ref A a
> to
> ref const A a
> 
> it turns into an endless loop.
> 
> My question is:
> Is this behavior intended?
> I know "const" is part of the type, but shouldn't recognize the
> compiler this case?

It's intended. constness matters more than refness when selecting a function 
overload. From the docs ( http://dlang.org/function.html#<u>function</u>-
overloading ):

-----
Func­tions are over­loaded based on how well the ar­gu­ments to a func­tion 
can match up with the pa­ra­me­ters. The func­tion with the best match is se­
lected. The lev­els of match­ing are: 

no match
match with im­plicit con­ver­sions
match with con­ver­sion to const
exact match
-----

So, you need to put const on the parameters for both functions, or you need to 
create other overloads which do. In general, if you're overloading on ref, 
make sure that the constness matches, or you're going to get infinite 
recursion. So, if you're mixing const and ref, then you're probably either 
going to want 4 different overloads (non-ref, ref, const non-ref, const ref) or 
2 overloads which use inout instead of const (inout and inout ref).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list