c++ assign a class member function a lambda function for computation efficiency [duplicate]

 ̄綄美尐妖づ 提交于 2020-01-30 06:29:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!