Array initialization with Struct templates

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 30 23:55:19 PDT 2015


On Monday, 31 August 2015 at 05:47:31 UTC, Ali Çehreli wrote:
> On 08/30/2015 10:38 PM, Jonathan M Davis via 
> Digitalmars-d-learn wrote:
>> On Monday, August 31, 2015 04:57:05 WhatMeWorry via 
>> Digitalmars-d-learn wrote:
>>>
>>> This seemingly trivial array initialization has caused me 
>>> hours
>>> of grief.
>>>
>>> enum Purpose { POSITIONAL, COLOR_ONLY, COLOR_AND_ALPHA,
>>> GENERIC_TRIPLE, GENERIC_QUAD }
>>> Purpose purpose;
>>>
>>> struct Chameleon(T, Purpose p)  // template
>>> {
>>>       static if (is (p == POSITIONAL)) {
>>>           T  x, y, z;
>>>       } else static if (is (p == COLOR_ONLY)) {
>>>           T  r, g, b;
>>>       } else static if (is (p == COLOR_AND_ALPHA)) {
>>>           T  r, g, b, a;
>>>       }  else static if (is (p == GENERIC_TRIPLE)) {
>>>           T  a, b, c;
>>>       } else static if (is (p == GENERIC_QUAD)) {
>>>           T  a, b, c, d;
>>>       }
>>> };
>>>
>>> struct VertexData
>>> {
>>>       Chameleon!(float, purpose.POSITIONAL)  position;
>>>       Chameleon!(float, purpose.COLOR_ONLY)  color;
>>> }
>>>
>>> alias Vert = VertexData;
>>>
>>> VertexData[] vertices =
>>> [
>>>       Vert(1.0, 1.0, 1.0, 0.0, 0.0, 0.0)  // compiler error 
>>> here
>>> ];

I would drop chameleon all together and just add the fields 
directly to VertexData, but make Purpose flag-based.

enum Purpose {
    position = 0x00,   // Assuming all verts have a position
    colorOnly = 0x01,
    colorAlpha = 0x02,
    triple = 0x04,
    quad = 0x08
}

enum hasColorOnly(Purpose p) = (p & Purpose.colorOnly) == 
Purpose.colorOnly;
struct VertexData(T, Purpose purpose){
    T x, y, z;
    static if(hasColorOnly!purpose)
       T r, g, b;
    ...
}

Then you can templatize your batches or meshes, or whatever you 
use to represent vertex objects, on the VertexData type.

alias ColorVertexf = VertexData!(float, Purpose.colorOnly);
auto batch = new Batch!(ColorVertexf);





More information about the Digitalmars-d-learn mailing list