小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

C++調(diào)用lua函數(shù)的通用call,參數(shù)數(shù)目任意、參數(shù)類型任意

 quasiceo 2014-01-13

C++調(diào)用lua函數(shù)的通用call,參數(shù)數(shù)目任意、參數(shù)類型任意  

2012-10-23 13:07:53|  分類: C++ |  標(biāo)簽:lua  bind  c++temlate  trait  參數(shù)   |字號 訂閱

我們只要用過一些成熟的lua對c++的綁定,例如SLB、luabind或者其他,就會想:為什么它們會這么神奇,可以在C++實(shí)現(xiàn)參數(shù)數(shù)目任意、參數(shù)類型任意的函數(shù)?,F(xiàn)在我們來探討它們的本質(zhì),這里只討論它們的最初原型,當(dāng)然現(xiàn)實(shí)的bind會非常復(fù)雜。

例如:實(shí)現(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ù)

將我們后面討論的方法稍稍修改下,也可以實(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 *類型 無法從這里實(shí)例化,WHY

template<>

struct Trait<char*>

{

       static void Do(chart)

       {

              std::cout<<" Type char* "<<t ;

       } 

};

 

//奇怪的是 char *類型 無法從這里實(shí)例化 WHY

template<>

struct Trait<char const*>

{

       static void Do(char constt)

       {

              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 T1typename T2>

void Call(T1 t1T2 t2)//自動推導(dǎo)

{   

      // 在函數(shù)內(nèi)部,T1、T2已經(jīng)被推導(dǎo)出來了,因此后面可以直接T1、T2來實(shí)例化其他的模版  

    //銜接前后    

       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);      

};


實(shí)現(xiàn)的效果:

Call(11,1111);

Call("hello","world");

Call("HelloGuys");

Call(11, 22.2, 232.3f, std::string("fdsaf"));

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多