您的位置:首頁>正文

用C++11實現C++17的apply

標題有點錯誤, apply是用tuple做參數, 調用一個函數。 這個標題是為了能更好的適配搜索關鍵字。

動態陣列用作函數參數更適合嵌入了腳本環境的C++程式, 比如lua或javascript(js)。

若有疏忽或改進, 請評論, 謝謝。

VS2017雖然實現了一些C++17特性, 但沒有apply(也許我沒發現或有替代), 而且即使以後更新添加了, 也不是很滿足我提到的陣列轉參數清單。

下面是VS2015.3測試通過的代碼。

寫腳本封裝(Wrapper)功能一般都是把C++函數(一般是成員函數)註冊到腳本的環境, 我看了很多開源作者都重載了很多範本類/範本函數, 其實都挺類的, 雖然都是一些體力活, 但一旦修改就是批量的。

本文參考了stackoverflow的Johannes Schaub的回復, 附錄有連結。

代碼中的intint只是一個自動轉換例子而已, 什麼也沒做, 你可以替換為你的腳本物件轉原生物件的轉換器。

代碼的核心部分是嵌套的範本類繼承, 這一段比較燒腦子:

templatestruct seq {}; template struct gen_seq : gen_seq {};// 嵌套繼承, 為了得到一個N-M至N的參數序列, 是無限的 template struct gen_seq { typedef seq type; };// 特例。 對上面嵌套繼承的一個終止, 終止條件是1開始到N

全部代碼, 無輸出, 請自行添加, 同樣, 也不需要其它標頭檔:

struct intint { int i; intint(int i) :i(i) {} operator int { return i; } }; templatestruct seq {}; template struct gen_seq : gen_seq {}; template struct gen_seq { typedef seq type; }; template struct callable { typename gen_seq::type fo; R(T::*func)(TS...); callable(R(T::*func)(TS...)) :func(func) {} template void call(seq, int* v) { (new T->*func)(intint(v[S])...); } void operator(T*, int* v) { call(fo, v); } }; struct foo { void func(int, int, int, int) { } }; int main { callable c(&foo::func); int v = { 100,200,300,400,500,600 }; c(new foo, v); return 0; }
同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示