Type value

Ali Çehreli acehreli at yahoo.com
Tue Dec 11 01:05:46 PST 2012


On 12/10/2012 11:54 AM, Zhenya wrote:

 > In some previous post I asked about possibility of declar opIndex,that
 > return type.

TypeTuple helps with that.

 > I thoght about it,and I understood that code like this is legal:
 >
 > struct Type(T)
 > {
 > alias T m_type;
 > alias m_type this;

For that to work, m_type must be an actual value. It can be a member 
variable or a member function that returns a value.

 > }
 >
 > void main()
 > {
 > Type!int Int;
 > // Int a;
 > }
 >
 > Is it hard to implement possibility of using Int as a type?
 > It would allow functions,that return types:)

It is possible to select a type by an index at compile time. It feels 
natural to me that the index is applied by the template instantiation 
syntax as in Type!0, as opposed to Type[0]:

import std.typetuple;

/* A test struct */
struct S
{
     string s;
     int i;
}

/* A test class */
class C
{
     S s;
     int i;
     double d;

     this(S s, int i, double d)
     {
         this.s = s;
         this.i = i;
         this.d = d;
     }
}

/* A mapping from type index to a type */
template Type(size_t index)
{
     alias TypeTuple!(int, double, S, C)[index] Type;
}

/* A generic function that can make an object of any type. */
Type!index make(size_t index, T...)(T args)
{
     static if (is(Type!index == struct)) {
         /* structs are not constructed by 'new' */
         return Type!index(args);

     } else static if (is(Type!index == class)) {
         /* classes are constructed by 'new' */
         return new Type!index(args);

     } else {
         /* Fundamental types must be made differently; probably due to 
syntax
          * issues. I would have expected for the following to work:
          *
          *     return Type!index(args);  // <-- compilation error
          */
         Type!index result;
         result = args[0];
         return result;
     }
}

void main()
{
     Type!0 i;
     Type!1 d;
     Type!2 s;
     Type!3 c;

     static assert(is (typeof(i) == int));
     static assert(is (typeof(d) == double));
     static assert(is (typeof(s) == S));
     static assert(is (typeof(c) == C));

     i = make!0(42);
     d = make!1(1.5);
     s = make!2("hello", 10);
     c = make!3(S("world", 100), 44, 10.75);
}

Actually, the [0] syntax is also possible as TypeTuple enables:

     alias TypeTuple!(int, double, S, C) MyTypes;
     MyTypes[0] i;

Ali



More information about the Digitalmars-d-learn mailing list