4

UPDATED: (Rephrased). 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.

One recommended solution uses #include <functional> and function<void()>, as shown in the simple test example:

#include <iostream>
using namespace std;

struct Number {
  int n;
  function(void()) doIt;

  Number(int i):n(i) {};

  void makeFunc() {

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

    // compiles but produces bloated code, not computatinally efficient
      if (n%2) doIt = _odd;   
      else     doIt = _even;  
  };
};

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

I'm finding that the compiled code (i.e. debug assembly) is grotesquely complicated and presumably NOT computationally efficient (the desired goal).

Does someone have an alternative construct that would achieve the end goal of a computationally efficient means of conditionally defining, at run-time, a class member function.

codechimp
  • 1,509
  • 1
  • 14
  • 21
  • 1
    Did you try to replace `void (*doIt)();` with `std::function doIt;`? – πάντα ῥεῖ Oct 28 '15 at 16:30
  • If you have a new question, post a new question. This one cannot get any new answers. – n. m. could be an AI Oct 28 '15 at 18:09
  • When you're saying it's not efficient, what was the baseline code you were comparing the *performance* against? It's a rhetorical question, I know you didn't. What I'm saying: you should. – Karoly Horvath Oct 28 '15 at 18:31
  • "I'm finding that the compiled code (i.e. debug assembly) is grotesquely complicated and presumably NOT computationally efficient" Don't presume, benchmark. And bloated assembly code does not imply inefficiency; generally quite the opposite. – Ian Kemp Oct 28 '15 at 20:32

1 Answers1

3

A capturing lambda expression cannot be assigned to a regular function pointer like you have.

I suggest using

std::function<void()> doIt;

instead of

void (*doIt)(); 
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • "cannot be assigned" - An that's because the type of a lambda is not utterable, so you cannot assign it to something which has a type. You need a construct that does type erasure. – Karoly Horvath Oct 28 '15 at 16:31