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);}
};
我可以看看甚至一个类型列表替换类型占位符v0
v1
v2
。 的东西,我想反正分享...
不作为类(模板非类型参数,其类型被推断相对经常被请求)。但是你可以使用一个函数模板,并将函数指针作为运行时参数传递(依靠编译器优化来移除该间接寻址)或将其包装在一个lambda中。 – dyp 2014-11-21 23:35:49
相关:http://stackoverflow.com/q/26655685 – dyp 2014-11-21 23:36:53
Duplicate:http://stackoverflow.com/q/19857444 http://stackoverflow.com/q/14710842 http://stackoverflow.com/q/15983802 (还有更多) – dyp 2014-11-21 23:37:52