Simple template constraint question
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 19 11:56:09 PDT 2015
On Saturday 19 September 2015 19:09, WhatMeWorry wrote:
> And a more open ended question. Is there a more elegant solution
> for the
> below function? Maybe a one-liner? I have a knack for making
> simple solutions
> complex :)
>
>
>
> // Calculate the number of components for openGL generic
> // vertex attribute. Must be 1, 2, 3, 4.
>
> // isAggregateType constraint accepts class, union, struct, and
> interface
>
> int getNumberComponents(T)(T someStruct) if (isAggregateType!(T))
> {
> int members = 0;
> foreach (i, member; someStruct.tupleof)
> {
> //writefln("Member %s:", i);
> //writefln(" type : %s", typeof(member).stringof);
> //writefln(" value: %s", member);
> members++;
> }
> return members;
> }
If the whole goal is to get how many members T has:
----
template getNumberComponents(T) if (is(T == struct))
{
enum getNumberComponents = T.tupleof.length;
}
----
Or you can write `T.tupleof.length` directly, of course.
More information about the Digitalmars-d-learn
mailing list