I have tried to build code which passes a function to be used within another function. Below is the code I tried, and it works OUTSIDE the function (so if I delete everything related to class Foo, it works), but I have no idea how to get this to work within the class itself. How can I pass one function within the class along? I tried with this->part1_math_class, Foo::part1_math_class and part1_math_class, none worked.
// Example program #include <iostream> #include <string> #include <stdint.h> #include <functional> int64_t loop(std::string partialMath, std::function<int64_t(std::string)> recurse) { while (partialMath.find("(") != std::string::npos) { auto posClose = partialMath.find(")"); auto posOpen = partialMath.rfind("(", posClose); std::string sub = partialMath.substr(posOpen + 1, posClose - posOpen - 1); int64_t resultInner = loop(sub, recurse); partialMath.replace(posOpen, sub.size() + 2, std::to_string(resultInner)); } return recurse(partialMath); } int64_t part1_math(std::string math) { return 0; } int64_t part2_math(std::string math) { return 1; } class Foo { public: Foo() { } int64_t loop_class(std::string partialMath, std::function<int64_t(std::string)> recurse) { while (partialMath.find("(") != std::string::npos) { auto posClose = partialMath.find(")"); auto posOpen = partialMath.rfind("(", posClose); std::string sub = partialMath.substr(posOpen + 1, posClose - posOpen - 1); int64_t resultInner = loop_class(sub, recurse); partialMath.replace(posOpen, sub.size() + 2, std::to_string(resultInner)); } return recurse(partialMath); } int64_t part1_math_class(std::string math) { return 2; } int64_t part2_math_class(std::string math) { return 3; } int64_t runLoop() { return loop_class("(1 + 2)", Foo::part1_math_class); } }; int main() { std::cout << loop("(1 + 2)", part1_math) << std::endl; // this one works Foo bar; std::cout << bar.runLoop() << std::endl; // this one does not even compile return 0; }
return loop_class("(1 + 2)", [this](std::string math) { return part1_math_class(math); });std::functioncan be used with functions as well as functors. In this case, the lambda provides the matching functor (correct signature) and binds (captures)thisas member.