问题
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.
回答1:
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)();
来源:https://stackoverflow.com/questions/33396424/c-assign-a-class-member-function-a-lambda-function-for-computation-efficiency