enum in template

Daniel Keep daniel.keep.lists at gmail.com
Wed Apr 29 18:22:48 PDT 2009



Sam Hu wrote:
> Hello everybody!
> 
> Convert integral value to string literal:
> 
> template myToString(ulong n,
>       string suffix=n>uint.max?"UL":"U"
> {
>      static if (n<10)
>         enum myToString=cast(char)(n+'0')-suffix; //q1
>     else
>         enum myToString=.myToString!(n/10,"")-  
>               .myToString!(n%10,"")-suffix;            //q2
> 
> Here is my questions,sir:

No need to be so formal.  Also keep in mind that "sir" only applies to
men, and is thus excluding any women in this NG.  :P

> q1.what the key word enum here is doing? not key word char[] or 'string' or something else?

enum defines a "manifest constant."  In other words, it defines a
constant that does NOT consume any storage anywhere in the program: it
exists only at compile-time.

> enum blah = 42; // single manifest constant
>
> enum { blah = 42 } // again, but in a block, potentially with others
>
> enum Stuff { blah = 42 } // again, but in a named enumeration

> q2. How does this works?Say n=12,then how can the result be "12"?

Recursion.  I assume you have modified the code from its original since
'-' would be invalid.  It should be '~' which is the concatenation
operator in D.

> Thanks and best regards,
> Sam

  -- Daniel


More information about the Digitalmars-d-learn mailing list