D語言泛型

來源:互聯網
上載者:User

比C++容易的泛型。

看看下面簡單的例子:

module testContainer;import std.stdio;import std.container;void main(){SList!int myList;foreach(i;0..10){myList.insert(i);}foreach(element;myList){writeln(element);}}

現在來定義個User類,放入SList中:

module freebird;import std.string;class User{private:string name;public:void setName(string argName){name = argName;}string getName(){return name;}}main.d file:module testContainer;import std.stdio;import std.container;import std.format;import freebird;import std.conv;void main(){SList!User users;foreach(i;0..10){string part1 ="name";string part2 = to!string(i);string name = part1 ~ part2;User user = new User();user.setName(name);users.insert(user);}foreach(curUser;users){writeln(curUser.getName());

編寫自己的模板,有一個Users類,內部管理了很多User對象。可以用在多線程和單線程環境下,因此接受一個模板策略類Lock。

main.d檔案

void main(){alias UserTemplate!(MutexLock).Users UsersType;UsersType users = new UsersType();foreach(i;0..10){string part1 ="name";string part2 = to!string(i);string name = part1 ~ part2;User user = new User();user.setName(name);users.add(user);}foreach(curUser;users.getValues()){writeln(curUser.getName());}}

users.d檔案

module freebird.users;import std.container;import freebird.user;//Pass MutexLock if you are in multi-thread context//Pass NoneLock if you are in single-thread contexttemplate UserTemplate(Lock){class Users{private:SList!User values;Lock l;public:this(){l = new Lock();

lock.d檔案

module freebird.lock;import std.stdio;class MutexLock{public:void lock(){writeln("mutex lock");}void unlock(){writeln("mutex unlock");}};class NoneLock{public:void lock(){writeln("nothing lock");}void unlock(){writeln("nothing unlock");}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.