微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Curry 一个在 CPP 中接受抽象参数的函数

如何解决Curry 一个在 CPP 中接受抽象参数的函数

我想对一个接受抽象参数的函数进行柯里化。这让我的编译器生气:

#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));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。