1

I'm having issues passing a function as an argument in C++. I've recreated a minimal working example here:

#include <iostream>
using namespace std;

void print(const double &func(double)) {
  cout << func(1) << endl;
}

class Obj {
  public:
  double MyFunction(double x);
  void PrintFunction();
};

void Obj::PrintFunction(){
  print(MyFunction);
}

double Obj::MyFunction(double x) {
  return x + 1;
}

int main() {
  Obj object;
  object.PrintFunction();
}

The overall structure seems weird in this context, but it makes more sense in the full code (specifically, I'm ideally looking for a solution that doesn't involve restructuring the function ownership). This compiles with the error error: invalid use of non-static member function double Obj::MyFunction(double), which suggests that there's something wrong with how I'm calling print(MyFunction). I have a rough understanding that MyFunction cannot be called by itself, but no amount of inclusions of pointers, references, etc., have successfully gotten the code to compile. How should I properly call MyFunction?

Henry Shackleton
  • 351
  • 2
  • 11
  • I compiled a complete minimal example with two approaches, check it out [online](https://wandbox.org/permlink/tQWAPjOtqfOs2rA3). Inspired by this [answer](https://stackoverflow.com/a/51790263/2411320). – gsamaras Dec 06 '19 at 19:46

1 Answers1

5

You can use std::bind to pass member methods.

#include <iostream>
#include <memory>
#include <functional>

void print(std::function<double(double)> f) {
    std::cout << f(1) << std::endl;
}

class Obj {
  public:
  double MyFunction(double x);
  void PrintFunction();
};

void Obj::PrintFunction(){
    auto t = std::bind(&Obj::MyFunction,this,std::placeholders::_1);
    print(t);
}

double Obj::MyFunction(double x) {
  return x + 1;
}

int main() {
  Obj object;
  object.PrintFunction();
}

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Irelia
  • 3,407
  • 2
  • 10
  • 31