D語言遊戲編程(11):D語言基礎之模板和混入(mixin)技術

來源:互聯網
上載者:User
    D語言通過模板,很好的支援泛型程式設計。與C++的模板相比較,各有優略。總體上說,D語言的模板在很多方面還是很方便的。
    D語言還支援模板的混入(mixin),簡單的講就是把模板執行個體化之後,將模板中的代碼插入到當前的位置。這是一個非常方便的工具!
    具體的,請看下面的示範代碼。

import std.stdio;

void main()
...{
    tryTemplate();
    tryMixin();
}

// template
//---------------------------------------------
template MyMathLib(float_t)
...{
    // struct, class模板
    struct Vector2
    ...{
        float_t x, y;
        
        static Vector2 opCall(float_t _x, float_t _y)
        ...{
            Vector2 ret;
            ret.x = _x;
            ret.y = _y;
            return ret;
        }
        
        Vector2 opAdd(in Vector2 v)
        ...{
            Vector2 ret;
            ret.x = x + v.x;
            ret.y = y + v.y;
            return ret;
        }
    }
    
    // 模板函數
    float_t dot(in Vector2 v1, in Vector2 v2)
    ...{
        return v1.x*v2.x + v1.y*v2.y;
    }
}

// 函數模板的另外一種寫法
T Square(T)(T t)
...{
    return t*t;
}


// 類模板的另外一種寫法
class Vector3(T)
...{
    T  x, y, z;
}



void tryTemplate()
...{
    alias MyMathLib!(float).Vector2 Vector2f;
    
    Vector2f v1 = Vector2f(1, 2);
    Vector2f v2 = Vector2f(3, 4);
    Vector2f v3 = v1 + v2;
    writefln("x = ", v3.x, ", y = ", v3.y);
    
    float d = MyMathLib!(float).dot(v1,v2);
    writefln("d = ",d);
    
    float f = 2;
    f = Square(f);    // 調用模板函數
    writefln(f);
    
    Vector3!(float) vv = new Vector3!(float);
    
}

// mixin
//-------------------------------
template MyMixin()
...{
    void Foo()
    ...{
        writefln("MyMixin.Foo");
    }
}

template MyMixin2(T)
...{
    T x;
}

class MyClass
...{
    mixin MyMixin2!(int);
    mixin MyMixin;
}

void tryMixin()
...{
    MyClass c = new MyClass;
    c.Foo();
    writefln(c.x);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.