2014-11-21 77 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); 
} 
相关问题