mercredi 28 octobre 2015

c++ assign a class member function a lambda function

I'm looking to boost the computation efficiency of my code by make an run-time assignment of a class member function to one of many functions conditional on other class members. I would like to use lambda function, but I need help with a compile-time error.

I've created a simple test example:

#include <iostream>
using namespace std;

void foo() { /* do some generic number operator */ };

struct Number {
  int n;
  void (*doIt)();  // must be able to operate on this->n

  Number(int i):n(i) {
    doIt = foo;  // test function pointer, this works fine
  };

  void makeFunc() {

      auto _odd  = [this]() { /* op specific to odd */ };
      auto _even = [this]() { /* op specific to even */ };

      // test the lambda functions, works fine
      if (n%2) _odd();   
      else _even();

      // this is the desire goal, but does NOT compile
      if (n%2) doIt = _odd;   
      else     doIt = _even;  
  };
};

int main() {
  int i;
  cin >> i;
  Number e(i);
  e.makeFunc();
  e.doIt();
};

Assigning the function doIt to a generic function foo (in the class constructor) works fine and the lambda functions, _odd and _even themselves, work fine. But I cannot figure out how to assign either of them to doIt. The compile-time error I get is

error: cannot convert ‘Number::makeFunc()::__lambda0’ to ‘void (*)()’ in assignment

if (n%2) doIt = _odd;

I'm at a loss. I'm just discovered lambda function, but most of the discussion seem to focus on for-each operators or callback functions. It is not clear to me, from those discussion, how to fix my problem. What ever the solution, the operator must have access this.

Aucun commentaire:

Enregistrer un commentaire