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

ag0aep6g anonymous at example.com
Mon Jan 11 16:56:05 UTC 2021


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) { ... }


More information about the Digitalmars-d-learn mailing list