所以,我努力學習模板元編程更好,我想這是一個很好的鍛鍊吧。
我試着寫代碼,可以回調函數與任意數量的我喜歡傳遞給它的參數。
// First function to call int add(int x, int y) ; // Second function to call double square(double x) ; // Third func to call void go() ;
回調創建的代碼應該是這樣的:
// Write a callback object that // will be executed after 42ms for "add" Callback<int, int, int> c1 ; c1.func = add ; c1.args.push_back(2); // these are the 2 args c1.args.push_back(5); // to pass to the "add" function // when it is called Callback<double, double> c2 ; c2.func = square ; c2.args.push_back(52.2) ;
我在想什麼,使用模板元編程我希望能夠宣佈像回調,寫這樣一個結構(請記住,這是非常僞代碼)
<TEMPLATING ACTION <<ANY NUMBER OF TYPES GO HERE>> > struct Callback { double execTime ; // when to execute TYPE1 (*func)(TYPE2 a, TYPE3 b) ; void* argList ; // a stored list of arguments // to plug in when it is time to call __func__ } ;
因此,當與
呼籲Callback<int, int, int> c1 ;
您將自動獲得由< HARDCORE模板ACTION >像
struct Callback { double execTime ; // when to execute int (*func)(int a, int b) ; void* argList ; // this would still be void*, // but I somehow need to remember // the types of the args.. } ;
在正確的方向的任何指針一個struct構建你上手就寫這個?
變量模板是C++ 0x的一部分。一個支持它們的編譯器(或者甚至是一個支持更少C++ 0x的編譯器)也將包含C++ 0x函數對象和'std :: bind',它與'boost :: bind'相似,並且實現了你所要做的談論。 – Potatoswatter