Question on Octal

Jonathan M Davis jmdavisProg at gmx.com
Wed Aug 15 11:07:59 PDT 2012


On Wednesday, August 15, 2012 19:49:53 Michael wrote:
> Hi all,
> I have just read Walter's article about octals on Dr. Dobb's.
> As a newbie, I tried to create one myself.
> 
> template octal(int n) {
> int toOct(int x) {...}
> 
> enum octal = toOct(n);
> }
> 
> void main() {
> import std.stdio : writeln;
> writeln(octal!10);
> }
> 
> I have two questions about this.
> 1) The specification is clear that the if the template has only
> one member and the member has the same name with the template's,
> the member is implicitly referred to in the instantiation. The
> template octal has two members, so the program should not really
> be compiling, and yet it does. Is this a compiler bug?

If the spec says that you can only have one member in an eponymous template, 
then it's wrong and needs to be updated. All of the symbols which don't match
the template name are private and are used only as helpers. TDPL (The D
Programming Language by Andrei Alexandrescu) gives the correct description.

> 2) I chose the declare the inner "octal" as an enum following
> Walter's example. But why enum? What would be different if it
> were auto, immutable, or static?

Normally, enum is used for values and alias is used for types. You _can_ use 
other stuff like auto if the result is a value, but if it doesn't generate a 
compile-time constant (which pretty much only enum and immutable will do), 
then it won't work in any context where the result must be known at compile 
time. And if you use immutable rather than enum, then that forces the result 
to be immutable, which may or may not be desirable. I don't think that I've 
ever seen anyone use anything other than enum or alias for the symbol which is 
the result of an eponymous template.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list