alias vs enum for lambdas?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu May 1 09:47:52 UTC 2025


On Sunday, April 27, 2025 10:59:24 PM MDT Orion via Digitalmars-d-learn wrote:
> In which programming scenarios should alias be used instead of
> enum?
>
> So far I have only found a simplified notation of a generic
> lambda:
> alias id = (x) => x; x; , which does not work in the case of enum.
>
> There is also a difference in overloading a non-generic lambda:
>
> alias m = (int x) => x;
> alias m = (float x) => 0.5 + x;
> - alias overloads a function with the same name.
>
> enum e = (int x) => x;
> ///enum e = (float x) => x; //error
> - enum does not.
>
> At the compiler level, enum lambda is represented as a literal.
> But how is alias represented? As an expression?

Aliases create an alternate name for a symbol (including types), whereas
enums are values which have no address (rather their value is essentially
copy-pasted when they're used).

So, enums are essentially variables except that they have no storage
associated with them, whereas aliases just give names to things. And the
name of an alias is replaced with the original name whenever the alias is
used.

So, if you alias a function, it makes sense that you can have overloads.
It's just the same function with a different name. Lambdas are a bit weird
in that respect in that they're anonymous, but the alias is giving them
names, and as such overloading makes sense.

However, an enum must be a value, and a function is not a value. A function
pointer could be, but a function cannot be - and neither can a lambda,
because a lambda is an anonymous function, not a function pointer.
Basically, if it doesn't make sense for something to be assigned to a
variable, then it doesn't make sense for it to be an enum.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list