www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - IDEA: "scope" for "bag of constants" (was: enum)

There has been some discussion that we need to separate the idea of 
"enumeration" (unique identifiers, the value of which the programmer 
doesn't care about) from "bag of constants" (related constants which the 
programmer needs to define).  Right now, both are (or, at least, can be) 
declared using an enum.

We all know that you can define constants as globals (though we're 
arguing about the syntax for it), so I'll skip over that.  Let's first 
look at the problem of how to define constants when you *don't* want 
them global (you want to organize them into a group).  You can already 
do this using a struct, though it's ugly:

   struct MyBagOfConstants {
     static invariant uint FIRST_CONSTANT  = 1;
     static invariant uint SECOND_CONSTANT = 10;

NOTE: I'm not using any "manifest constant" syntax, even though I want 
to, because I'm not up-to-date on the latest syntax.  (sigh)

It's ugly because when we see a struct we think of it as something which 
  can be instantiated.  This struct, however, is only used for scoping. 
  So let's allow the keyword scope to define that sort of thing - a 
scope for variables which cannot be instantiated:

   scope MyBagOfConstants {
     invariant uint FIRST_CONSTANT  = 1;
     invariant uint SECOND_CONSTANT = 10;

(Yeah, I know that "scope" here is leaning towards the C++ concept of 
"namespace".  But we already support modules-as-namespaces and 
structs-as-namespaces.  Perhaps 
subset-of-a-module-but-not-a-struct-as-namespace makes sense, too.)

This leaves enum to store only true (value unknown to the programmer) 

Ofc, it doesn't leave us any easy way to define "something which 
includes both scoped constants and a storage type" like enum does:

   enum Foo : uint { .... }

...but I'm skeptical of that anyhow.  YMMV, but I have only encountered 
the need for that when I'm implementing fields to read/write binary file 
formats.  If we really *had* to implement it, I would lean toward using 
typedef or alias for that:

   typedef uint ThisUsedToBeCalledAnEnum {
     ... list of constants of this type ...
Jan 02 2008