我們只要用過一些成熟的lua對c++的綁定,例如SLB、luabind或者其他,就會想:為什么它們會這么神奇,可以在C++實現(xiàn)參數(shù)數(shù)目任意、參數(shù)類型任意的函數(shù)。現(xiàn)在我們來探討它們的本質(zhì),這里只討論它們的最初原型,當(dāng)然現(xiàn)實的bind會非常復(fù)雜。 例如:實現(xiàn)調(diào)用lua函數(shù)的通用方法; call("add",112, 2323.33); // 調(diào)用lua 的add方法,參數(shù)是一個整數(shù)和一個double call("print","helloworld");// 調(diào)用lua 的 print 方法,參數(shù)是一個C-style 字符串"helloworld" call("print",222222);// 調(diào)用lua 的 print 方法,參數(shù)是一個整數(shù) 將我們后面討論的方法稍稍修改下,也可以實現(xiàn)上面的神奇調(diào)用。 核心思想 對每種不同的參數(shù)類型 ,分別調(diào)用不同的處理函數(shù)Do() //原型要首先聲明 template<typename T> struct Trait { static void Do(T t); }; //利用偏特化 template<> struct Trait<int> { static void Do(int t) { std::cout<<" Type int "<<t ; } }; template<> struct Trait<float> { static void Do(float t) { std::cout<<"Type float "<<t ; } };
template<> struct Trait<double> { static void Do(double t) { std::cout<<" Type double "<<t ; } };
//char const *類型 無法從這里實例化,WHY template<> struct Trait<char*> { static void Do(char* t) { std::cout<<" Type char* "<<t ; } };
//奇怪的是 char *類型 無法從這里實例化 WHY template<> struct Trait<char const*> { static void Do(char const* t) { std::cout<<" Type char const* "<<t ; } };
template<> struct Trait<std::string> { static void Do(std::string t) { std::cout<<" Type std::string "<<t ; } };
關(guān)鍵的地方 template<typename T1, typename T2> void Call(T1 t1, T2 t2)//自動推導(dǎo) { // 在函數(shù)內(nèi)部,T1、T2已經(jīng)被推導(dǎo)出來了,因此后面可以直接T1、T2來實例化其他的模版 //銜接前后 Trait<T1>::Do(t1); Trait<T2>::Do(t2); }; template<typename T1,typename T2,typename T3 ,typename T4> void Call(T1 t1,T2 t2,T3 t3 ,T4 t4) { Trait<T1>::Do(t1); Trait<T2>::Do(t2); Trait<T3>::Do(t3); Trait<T4>::Do(t4); }; 實現(xiàn)的效果: Call(11,1111); Call("hello","world"); Call("HelloGuys"); Call(11, 22.2, 232.3f, std::string("fdsaf"));
|
|