Passing anonymous enums as function parameters
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sun Dec 17 12:19:21 UTC 2017
On Sunday, December 17, 2017 11:49:58 kerdemdemir via Digitalmars-d-learn
wrote:
> I have an enum statement :
>
> enum : string
> {
> KErdem
> Ali
> Zafer
> Salih
> //etc...
> }
>
>
> I don't want to give a name to my enum class since I am accessing
> this variables very often.
>
> But I also have a function like:
>
> double ReturnCoolNess( /* Is there any way? */ enumVal )
> {
> switch (enumVal)
> {
> case KErdem:
> {
> return 0.0
> }
> case Ali:
> {
> return 100.0;
> }
> case Salih:
> {
> return 100.0;
> }
> // etc..
> }
> }
>
> Is there any way I still keep my enum anonymous and be able to
> call functions with different enumarations. Or is there any other
> way to call named enums without type name ?
D does not have anonymous enums. Either you're declaring an enum which
creates a new type and therefore has a name and a base type, or you're just
creating manifest constants that don't create a new type. e.g.
enum MyEnum : string
{
a = "hello",
b = "foo",
c = "dog",
d = "cat"
}
vs
enum string a = "hello";
enum string b = "foo";
enum string c = "dog";
enum string d = "cat";
or
enum a = "hello";
enum b = "foo";
enum c = "dog";
enum d = "cat";
If you want a function to accept values that aren't tied to a specific enum,
then just have the function take the base type.
Now, within sections of code, you can use the with statement to reduce how
often you have to use the enum type's name, e.g.
with(MyEnum) switch(enumVal)
{
case a: { .. }
case b: { .. }
case c: { .. }
case d: { .. }
}
but you can't have an enum without a name or just choose not to use an
enum's name. With how enums work in D, there's really no point in having
them if you're not going to treat them as their own type or refer to them
via the enum type's name. If that's what you want to do, then just create a
bunch of manifest constants.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list