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 ):
-----
Functions are overloaded based on how well the arguments to a function
can match up with the parameters. The function with the best match is se
lected. The levels of matching are:
no match
match with implicit conversions
match with conversion 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