【问题标题】:Curry a function that takes abstract arguments in CPPCurry 一个在 CPP 中接受抽象参数的函数
【发布时间】:2021-05-19 13:35:39
【问题描述】:

我想 curry 一个带有抽象参数的函数。这让我的编译器很生气:

#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
}

有没有一种方法可以在不借助指针的情况下完成这项工作?

【问题讨论】:

    标签: c++ functional-programming abstract-class currying


    【解决方案1】:

    如果要柯里化一个函数,可以使用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';
    }
    

    但是,在您的情况下,您似乎是“部分”应用该功能,而不是对其进行柯里化。我使用引号是因为您实际上是在向它传递它需要的所有参数,而您只是在延迟调用。为此,您可以使用 &lt;boost/hana/functional/partial.hpp&gt; 标头中的 boost::hana::partial (但您仍然必须将对象包装在引用中,如 the other answer 所示,它实际上告诉您原始代码中有什么问题):

        using boost::hana::partial;
        const auto myCurriedFunction = partial(myFunction, std::ref(myChildObject));
    

    【讨论】:

      【解决方案2】:

      std::bind 复制它的参数,你可以使用 std::reference_wrapper 的引用

      const auto myCurriedFunction = std::bind(myFunction, std::ref(myChildObject));
      

      或使用 lambda:

      const auto myCurriedFunction = [&](){ return myFunction(myChildObject); };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-17
        • 1970-01-01
        • 2012-03-08
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多