Thread overview
How to determine constness at compile time?
Nov 27, 2007
Janice Caron
Nov 27, 2007
Janice Caron
November 27, 2007
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?

template constID(T)
{
    static if(is(T:invariant(T)[]))
    {
        static const int constID = 2;
    }
    else static if(is(T:const(T)[]))
    {
        static const int constID = 1;
    }
    else
    {
        static const int constID = 0;
    }
}

void main()
{
    writefln(constID!(string));
}

This prints 0. I would have expected (hoped for) it to print 2.
November 27, 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


November 27, 2007
That is genius! Sheer genius! Thank you.

I did ponder for a while why constID!() invoked realConstID!(), instead of doing it in a single template. So I did the experiment and found it wouldn't compile if you did it in a single template. I don't know why though!

Anyway, cheers!
November 27, 2007
"Janice Caron" wrote
> That is genius! Sheer genius! Thank you.
>
*blushes* :)

> I did ponder for a while why constID!() invoked realConstID!(), instead of doing it in a single template. So I did the experiment and found it wouldn't compile if you did it in a single template. I don't know why though!

I think it has something to do with the alias Y statement, because now constID is not the only member of the template.  I know you said this worked for you in the past, but maybe it was just luck that it worked :)

-Steve