问题描述
我想对一个接受抽象参数的函数进行柯里化。这让我的编译器生气:
#include <functional>
class MyAbstractParentClass {
public:
virtual void someVirtualMethod() = 0;
};
class MyConcreteChildClass: public MyAbstractParentClass {
public:
virtual void someVirtualMethod() override {}
};
void myFunction(const MyAbstractParentClass& myAbstractObject) {}
int main(int argc,const char * argv[]) {
const MyAbstractParentClass& myChildobject = MyConcreteChildClass();
myFunction(myChildobject); // all good here
const auto myCurriedFunction = std::bind(myFunction,myChildobject); // error here
myCurriedFunction(); // we never get here
}
有没有一种方法可以让我在不求助于指针的情况下完成这项工作?
解决方法
std::bind
复制其参数,您可以将引用与 std::reference_wrapper
const auto myCurriedFunction = std::bind(myFunction,std::ref(myChildObject));
或使用 lambda:
const auto myCurriedFunction = [&](){ return myFunction(myChildObject); };
,
如果你想柯里化一个函数,可以使用boost::hana::curry
,如下图:
#include <boost/hana/functional/curry.hpp>
#include <iostream>
int f(int x,int y,int z) {
return x + y + z;
};
int main {
auto constexpr f_curried = boost::hana::curry<3>(f);
auto constexpr f12 = f_curried(1)(2);
std::cout << f12(3) << '\n';
}
但是,在您的情况下,您似乎“部分”应用了该功能,而不是对其进行柯里化。我使用引号是因为您实际上将它需要的所有参数传递给它,而您只是在延迟调用。为此,您可以使用 boost::hana::partial
标头中的 <boost/hana/functional/partial.hpp>
(但您仍然必须将对象包装在一个引用中,如 the other answer 所示,它实际上告诉您原始文件中的错误代码):
using boost::hana::partial;
const auto myCurriedFunction = partial(myFunction,std::ref(myChildObject));