I have a C++ function that takes in two other functions as parameters:
// ParseResult is a class with a default constructor (no arguments)
ParseResult* bin_op(std::function<ParseResult*()> func_a, std::vector<std::string> ops, std::function<ParseResult*()> func_b);
When I call this function the following way:
bin_op(func_1, {"MOD"}, func_2);
// Both func_1 and func_2 are of type ParseResult*, and take in no parameters
the compiler throws this error:
no known conversion for argument 1 from '<unresolved overloaded function type>' to 'std::function<ParseResult*()>
My code editor shows this:
no suitable constructor exists to convert from "ParseResult *()" to "std::function<ParseResult *()>"
std::function
is included in the code.
What should I do? I have already tried solving this problem using templates and function pointers, but I failed to do so.
EDIT: Here is the simplified version of the codebase:
#include <iostream>
#include <vector>
#include <functional>
class ParseResult {
public:
ParseResult() {}
};
class Parser {
public:
ParseResult* c;
ParseResult* bin_op(std::function<ParseResult*()> func_a, std::vector<std::string> ops, std::function<ParseResult*()> func_b);
ParseResult* func_1();
ParseResult* func_2();
Parser() {
c = bin_op(static_cast<ParseResult*(*)()>(func_1), {"MOD"}, static_cast<ParseResult*(*)()>(func_2));
}
};
ParseResult* Parser::func_1() { return new ParseResult(); }
ParseResult* Parser::func_2() { return new ParseResult(); }
ParseResult* Parser::bin_op(std::function<ParseResult*()> func_a, std::vector<std::string> ops, std::function<ParseResult*()> func_b) {
ParseResult* a = func_a();
ParseResult* b = func_b();
return a;
}
int main() {
parser = new Parser();
std::cout << parser->c;
}
func_1
and func_2
are non-static member functions; they need objects to be called on. You can wrap them into lambdas with capturing this
. e.g.
c = bin_op([this]() { return func_1(); }, {"MOD"}, [this]() { return func_2(); });
LIVE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With