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.

4
  • 1
    Did you try to replace void (*doIt)(); with std::function<void> doIt;? Commented Oct 28, 2015 at 16:30
  • If you have a new question, post a new question. This one cannot get any new answers. Commented Oct 28, 2015 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. Commented Oct 28, 2015 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. Commented Oct 28, 2015 at 20:32

1 Answer 1

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)(); 
Sign up to request clarification or add additional context in comments.

1 Comment

"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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.