Easy way to accept X and immutable X in parameters without overloading?

Paul Backus snarwin at gmail.com
Mon Jan 11 19:30:25 UTC 2021


On Monday, 11 January 2021 at 18:51:04 UTC, Jack wrote:
> alias Callback = void function(const C, int);
>
> void main()
> {
>     auto l = SList!Callback();
>     auto a = (C c, int d) { };
>     auto b = (C c, int d) { };
>     auto c = (const C c, int d) { };
>     l.insert(a);
>     l.insert(b);
>     l.insert(c);
> }

You have a type mismatch. Changing the code to use explicit type 
annotations instead of `auto` makes the problem obvious:

alias Callback = void function(const C, int);

void main()
{
     Callback a = (C c, int d) { }; // Error
     Callback b = (C c, int d) { }; // Error
     Callback c = (const C c, int d) { };
}

The error message given is the same for both lines:

Error: cannot implicitly convert expression `__lambda1` of type 
`void function(C c, int d) pure nothrow @nogc @safe` to `void 
function(const(C), int)`

In other words, `a` and `b` are not valid Callbacks, because they 
take a mutable C argument instead of a const C argument.



More information about the Digitalmars-d-learn mailing list