c ++为类成员函数分配一个lambda函数以提高计算效率 [英] c++ assign a class member function a lambda function for computation efficiency

查看:140
本文介绍了c ++为类成员函数分配一个lambda函数以提高计算效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新:(改写).我希望通过在运行时将类成员函数分配给以其他类成员为条件的多个函数之一来提高代码的计算效率.

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.

一个推荐的解决方案使用#include <functional>function<void()>,如简单的测试示例所示:

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.

推荐答案

不能像您一样将捕获 lambda表达式分配给常规函数指针.

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

我建议使用

std::function<void()> doIt;

代替

void (*doIt)(); 

这篇关于c ++为类成员函数分配一个lambda函数以提高计算效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆