2013-06-26 28 views
4

我想定義一些結構中,每一個開始由同一部件密新模板:定義結構具有相同的成員

struct A { 
    S s; // same member 
    X x; // other members 
} 

struct B { 
    S s; // same member 
    Y y; // other members 
} 

什麼是一個mixin模板來實現這一目標?

回答

3
import std.array; 

struct S {} 
struct X {} 
struct Y {} 

mixin template Common() { 
    S s; // same member 
} 

string struct_factory(string name, string[] args...) { 
    return `struct ` ~ name ~ ` { 
       mixin Common; 
      ` ~ args.join("\n") ~ ` 
      }`; 
} 

mixin(struct_factory("A", "X x;")); 
mixin(struct_factory("B", "Y y;")); 

void main() { 
    A a; 
    B b; 
} 

或(隱藏字符串混入):

import std.array; 

struct S {} 
struct X {} 
struct Y {} 

private string struct_factory(string name, string[] args...) { 
    return `struct ` ~ name ~ ` { 
       mixin Common; 
      ` ~ args.join("\n") ~ ` 
      }`; 
} 

mixin template Common() { 
    S s; 
} 

mixin template Struct(string name, Args...) { 
    mixin(struct_factory(name, [Args])); 
} 

mixin Struct!("A", "X x;"); 
mixin Struct!("B", "Y y;"); 


void main() { 
    A a; 
    B b; 
} 
5
mixin template Common() { 
    S s; // same member 
} 

struct A { 
    mixin Common; 
    X x; 
} 

struct B { 
    mixin Common; 
    Y y; 
} 

Template Mixin

+0

有沒有辦法更緊湊地做到這一點?即包括模板中的結構語法 –

+0

@CoreXii但是爲什麼?這種語法本身就很簡潔,你幾乎不會得到任何簡潔,但會明顯影響可讀性。 – vines

0

一個稍微不同的看法大衛的回答:

//The actual building of the struct 
mixin template PrefilledImpl(string name, string common, string individual) 
{ 
    mixin("struct " ~ name ~ "{" ~ common ~ individual ~ "}"); 
} 

//A sort of template currying 
mixin template Prefilled(string templateName, string common) 
{ 
    mixin("mixin template " ~ templateName ~ 
      "(string name, string individual) {mixin PrefilledImpl!(name, \"" 
      ~ common ~ "\", individual);}"); 
} 

//declare the "prototype" for the struct 
mixin Prefilled!("StructWithInt", q{int a;}); 

//declare the actual struct type 
mixin StructWithInt!("MyStructA", q{double b;}); 


//and again for a different struct 
mixin Prefilled!("StructWithLots", q{float z; char[][] ns; ulong id;}); 
mixin StructWithLots!("MyStructB", q{void* data;}); 

void main() 
{ 
    MyStructA foo; 
    foo.a = 2; 
    foo.b = 4.65; 

    MyStructB bar; 
    bar.z = 3.2; 
    //etc..... 
} 

FYI將q {}語法是可選的,喲你可以通過正常的字符串來代替。

相關問題