Search code examples
c++functional-programmingabstract-classcurrying

Curry a function that takes abstract arguments in CPP


I would like to curry a function that takes an abstract argument. This makes my compiler angry:

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

Is there a way I can make this work without resorting to pointers?


Solution

  • std::bind copies its argument, you might use reference with std::reference_wrapper

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

    or use lambda:

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