Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method as function parameter

Tags:

c++

c++11

I'm trying to pass some class method to some function and take "function call missing argument list; use '& ' to create a pointer to member" error.

//There is some class
class A {
  int someField;
  void Add(int someAdd) {
    someField += someAdd;
  }
}

//And function
void someFunc(std::function<void(int x)> handler) {
  //Some code
  handler(234);
}

//Class method pass to function
void main() {
  A* instanceA = new A();
  someFunc(instanceA->Add); //Error 19  error C3867: 'A::Add': function call missing argument list; use '&A::Add' to create a pointer to member
}

What's wrong?

like image 996
Vovanok Avatar asked Dec 08 '22 17:12

Vovanok


2 Answers

C++ doesn't have bound methods as a language construct. Write:

someFunc(std::bind(&A::Add, instanceA, std::placeholders::_1));
like image 134
ecatmur Avatar answered Dec 11 '22 11:12

ecatmur


You need to use std::bind with place holder as you pass in parameter later:

#include <functional>
someFunc(std::bind(&A::Add, instanceA, std::placeholders::_1));

Also note, you need to make A::Add public

class A {    
  int someField;

public:
  void Add(int someAdd) {
    someField += someAdd;
  }
};

Also note, in C++ standard no void main

int main() 
{
    someFunc(std::bind(&A::Add, instanceA, std::placeholders::_1));
}
like image 44
billz Avatar answered Dec 11 '22 11:12

billz