2014-11-21 74 views
2

有沒有辦法重寫curry模板類的定義,所以main接受curry<addtogether>而不是當前的curry<int,int,int,addtogether>具有函數指針參數的模板類

#include<iostream> 

int addtogether(int x,int y){ 
    return(x+y);}; 

template<class T,class U,class V,T(*F)(U,V)> 
class curry{ 
private: 
    const U y; 
public: 
    curry(U x):y(x){}; 
    T operator()(V v){return(F(y,v));}; 
}; 

int main(){ 
    {using namespace std; 
    cout<<curry<int,int,int,addtogether>(1)(1);} 
}; 

addtogether是在編譯時已知這應該是可行的。我剛剛沒有看到許多帶有函數指針的模板。大多數形式是int(*f)(int,int),它不夠多態。我正在尋找一個模板定義,它將接受帶有兩個參數的任何函數指針。

謝謝!

編輯:如果我要問的確是不可能的,我認爲以下解決方法的:

#include<iostream> 

class addtogether{ 
public: 
    typedef int v1; 
    typedef int v2; 
    typedef int v0; 
    int operator()(int x,int y){ 
    return(x+y);}; 
}; 

template<class F> 
class curry{ 
public: 
    typedef typename F::v2 v1; 
    typedef typename F::v0 v0; 
    const typename F::v1 y; 
    curry(const typename F::v1 x):y(x){}; 
    v0 operator()(const v1 v){return(F()(y,v));}; 
}; 

int main(){ 
{using namespace std; 
    cout<<curry<addtogether>(1)(1);} 
}; 

我可以看看甚至一個類型列表替換類型佔位符v0v1v2。 的東西,我想反正分享...

+3

不作爲類(模板非類型參數,其類型被推斷相對經常被請求)。但是你可以使用一個函數模板,並將函數指針作爲運行時參數傳遞(依靠編譯器優化來移除該間接尋址)或將其包裝在一個lambda中。 – dyp 2014-11-21 23:35:49

+0

相關:http://stackoverflow.com/q/26655685 – dyp 2014-11-21 23:36:53

+0

Duplicate:http://stackoverflow.com/q/19857444 http://stackoverflow.com/q/14710842 http://stackoverflow.com/q/15983802 (還有更多) – dyp 2014-11-21 23:37:52

回答

2

有改寫curry模板類定義一種方式,以便main接受curry<addtogether>而不是當前curry<int,int,int,addtogether>

不,因爲非類型模板參數F依賴於較早的模板參數,所以不能在它們之前聲明。

您是否真的需要函數指針作爲類型的一部分,而不是作爲curry的成員變量存儲?使用成員變量將允許它在函數模板中推導出來:

template<class T,class U,class V> 
class curry{ 
private: 
    T (*f)(U,V); 
    const U y; 
public: 
    curry(T (*f)(U,V), U x): f(f), y(x){}; 
    T operator()(V v){return(f(y,v));}; 
}; 

template<class T,class U,class V> 
curry<T, U, V> 
make_curry(T (*f)(U,V), U u) 
{ 
    return curry<T, U, V>(f, u); 
} 
相關問題