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

Jack jckj33 at gmail.com
Mon Jan 11 18:51:04 UTC 2021


On Monday, 11 January 2021 at 18:37:58 UTC, ag0aep6g wrote:
> On Monday, 11 January 2021 at 18:12:17 UTC, Jack wrote:
>> thanks! now, how would I add const here?
>>
>> import std.container : SList;
>> auto l = SList!Callabck();
>>
>> doesn't work:
>>
>> auto l = SList!(const(Callabck()));
>> auto l = SList!(const Callabck());
>
> You said you want the callbacks to accept both mutable and 
> immutable. So make the parameter `const` in the callback type:
>
>     alias Callabck = void function(const X foo);

I did exactly that and SList template initilization failed

> If you wanted an `SList` of `const Callabck`s, you'd write that 
> like so:
>
>     auto l = SList!(const Callabck)();
>
> But it seems like `SList` doesn't support const elements. And I 
> don't think that's what you actually want anyways.

What I want is store a instance of Callback, whose parameter 
accept both immutable and non-immutable (so I used const) in the 
SList but it failed to initialize

>
> (By the way, you've got a typo there in "Callabck".)

oh i see but I did write this code just for this post anyway.

Here's what I'm trying to make to work:

import std.container : SList;

class C
{
     static immutable Foo = new C();
    // ....
}

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);
}





More information about the Digitalmars-d-learn mailing list