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

Jack jckj33 at gmail.com
Mon Jan 11 18:12:17 UTC 2021


On Monday, 11 January 2021 at 16:56:05 UTC, ag0aep6g wrote:
> On Monday, 11 January 2021 at 16:40:01 UTC, Jack wrote:
>> let's say a I have this:
>>
>> void f(X foo) { }
>>
>> but I'd like to make f() accept immutable X too so instead of 
>> cast away everywhere in the code where immutable(X) is passed 
>> to f() or make a overload for this, are there any way to 
>> accept both in same function? those function are callback-like 
>> functions, I have lots of them so already and would need to 
>> double, if I do add an overload just for the immutable. I did 
>> come up with something using templates, not sure if it's ugly:
>>
>> void f(T)(T x)
>> if(is(T == C) || is(T == immutable(C)) {
>> // ...
>> }
>
> Accepting both mutable and immutable is what `const` is for:
>
> void f(const X foo) { ... }

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





More information about the Digitalmars-d-learn mailing list