How to determine constness at compile time?

Steven Schveighoffer schveiguy at yahoo.com
Tue Nov 27 07:12:34 PST 2007


"Janice Caron" wrote
> I'm trying to write a template to determine the constness (or not) of
> array members. The following seemed the obvious thing to do, but it
> doesn't work. Anyone know how to do it right?
>

import std.stdio;

template realConstID(T)
{
        static if(is(T X : X[]))
                alias X Y;
        else static if(is(T X : X*))
                alias X Y;
        else
                alias T Y;

        static if(is(Y == invariant(Y)))
        {
                static const int constID = 2;
        }
        else static if(is(Y == const(Y)))
        {
                static const int constID = 1;
        }
        else
        {
                static const int constID = 0;
        }
}

template constID(T)
{
        static const int constID = realConstID!(T).constID;
}

void main()
{
        writefln(constID!(char[]));
        writefln(constID!(const(char)[]));
        writefln(constID!(invariant(char)[]));
        writefln(constID!(char*));
        writefln(constID!(const(char)*));
        writefln(constID!(invariant(char)*));
}


outputs:
0
1
2
0
1
2

-Steve 





More information about the Digitalmars-d mailing list