精華區beta CSSE 關於我們 聯絡資訊
※ 引述《reader (讀者)》之銘言: : struct A { : void f() { ... } : void g(ref t) { t; } : }; : ref b; : void f() { ... } : void g(ref t = b) { t; } // 可以使用預設參數 : ref b = { f(); }; // 寫成 ref b = f(); 也可以 : void main() { : A a; : g(b); // 執行 f() : a.g(b); // 執行 A::f(), 也可以寫成 a.g({ f(); }); 或 a.g(f()); : } 不過顯然地,這個機制是和動態連結衝突的,但樣板成員函式也是如此, 並沒有太特別。 重點是,這樣一來就可以簡單達成 delegation 了。 比較神秘的地方是 operator 可不可以使用這個功能? 我的看法是可以, 不過應該有較多限制,例如過載就不能使用了: class textfile { public: bool readline(int s, char* d); // read a line textfile& operator | (ref t) { char b[256]; while(readline(256, b)) t; return *this; } textfile(const char*); // open file }; void main() { textfile f("test.txt"); f | { printf("%s", b); }; // 把每一行列印出來 } 這樣子寫程式夠方便吧。如果要用前置處理的話,可能會變成這樣: class textfile { ... textfile _op_bit_or_1() { char b[256]; while(readline(256, b)) { printf("%s", b); } return *this; } }; void main() { textfile f("test.txt"); f._op_bit_or_1(); } 看起來並沒有什麼大問題。當然,程式碼的膨脹是免不了的, 那就是代價了,這和 template 的狀況也是類似的。 只是可以想見,這樣的前置處理程式,並不是很容易寫的。可能 我得找一段較空閒的時間來試試看。 另外還有幾個東西也可以嘗試著做成 C++ extension, 或許可以 先做一個前進半步的新程式語言,往後再來發展更進一步的程式 語言,而不必一步到位。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.222.173.26