Passing anonymous enums as function parameters

Jacob Carlborg doob at me.com
Sun Dec 17 16:46:27 UTC 2017


On 2017-12-17 12:49, kerdemdemir 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 ?

You have three options:

* Specify "string" as the type of the parameter for the ReturnCoolNess 
function. Note that this will allow any string to be passed to this function

* Use the "with" statement to avoid having to specify the enum name. 
This needs to be used in every place you want to access the enum members

enum Foo : string
{
     KErdem
     Ali
     Zafer
     Salih
     //etc...
}

double ReturnCoolNess(Foo enumVal )
{
     with(Foo)
         switch (enumVal)
         {
             case KErdem:
             {
                 return 0.0
             }
             case Ali:
             {
                 return 100.0;
             }
             case Salih:
             {
                 return 100.0;
             }
             // etc..
         }
}

* Use "alias" to make the enum members available without having to 
specify the enum name:

enum Foo : string
{
     KErdem
     Ali
     Zafer
     Salih
     //etc...
}

alias KErdem = Foo.KErdem
alias Ali = Foo.Ali
// etc...

Now you can access the enum members through the aliases. Specify "Foo" 
as the type of the parameter in the ReturnCoolNess function. Generating 
these alias can be automated with some metaprogramming and string mixins.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list