Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: conversion from overloaded function to std::function

Tags:

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.

  • Operating system: Windows 10 64-bit
  • Compiler: g++ 8.2.0

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;
}
like image 949
Bonfire Avatar asked Dec 26 '19 09:12

Bonfire


1 Answers

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

like image 122
songyuanyao Avatar answered Oct 12 '22 22:10

songyuanyao