Constants, Aliases
Bill Baxter
dnewsgroup at billbaxter.com
Wed Dec 13 23:28:21 PST 2006
Xinok wrote:
> In C++, you can define a constant by using a preprocessor:
> #define INT 30
>
> In D, the standard is to use 'const':
> const int INT = 30;
>
> The problem with the const keyword is it doesn't guarantee the expression will
> be constant.
> const int* PTR = new int; // This technically isn't a constant, the compiler
> just doesn't allow you to modify it's value.
>
> Another solution is to use enumerators, but they don't aloow any type other
> than int:
> enum { val = 30 } // OK
> enum { str = "Hello" } // Error
>
>
> So I was thinking, why not give this job to aliases? Aliases must be constant,
> you can use any type with them, and they're easy to write.
> alias 30 VAL;
> alias "Hello" STR;
> alias 31.5 DEC;
>
> Expressions can simply be put within parenthesis:
> alias (15 * 99) EXP;
It would also make writing recursive templates a little bit simpler.
Sometimes it takes me a minute to figure out whether I need
alias template_name[1..$] template_name;
or
const Type template_name = template_name[1..$];
Actually... I guess they're interchangeable till you get to the base
case -- ferinstance:
template tuple_all_of(T, S...) {
static if(S.length == 0) {
const bool tuple_all_of = true;
}
else static if( is(S[0]: T) ) {
// either version is ok here
//const bool tuple_all_of = tuple_all_of!(T, S[1..$]);
alias tuple_all_of!(T, S[1..$]) tuple_all_of;
} else {
const bool tuple_all_of = false;
}
}
--bb
More information about the Digitalmars-d
mailing list