带有函数指针参数的模板类

时间:2014-11-21 23:26:26

标签: c++ templates function-pointers currying

有没有办法重写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);}
};

我甚至可以通过类型列表替换类型占位符v0 v1 v2。 无论如何我想分享的东西......

1 个答案:

答案 0 :(得分: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);
}
相关问题