首页 > 解决方案 > 如何根据初始化参数修复类函数行为

问题描述

我正在创建一个 C++ 类,它在初始化期间采用某些参数,并具有一些基于其私有变量的函数,类似于compute这里的函数:

class A {
  public:
    A(int x){
      a = x;
    }
    int compute(int y){
      if (a == 0){
        return y*y;
      }
      else if (a == 1){
        return 2*y;
      }
      else{
        return y;
      }
    }
  private:
    int a;
};

// usage

A myA(1); // private variables set only once
myA.compute(10); // this will check value of a 
myA.compute(1); // this will check value of a

鉴于私有变量在初始化期间设置并且不会再次更改,有没有什么有效的方法可以避免在运行时与私有变量相关的条件检查?

感谢您提供任何和所有帮助。谢谢

标签: c++functionclassruntime

解决方案


如果您将使用例如函数对象作为成员,则可以避免条件检查,并根据变量 a 的值进行设置。无论如何,我认为条件检查不会是大的性能问题。但这当然取决于您的应用程序。

#include <functional>
#include <iostream>

class A {
  public:
    A(int x)
    : a { x } 
    {
      if (a == 0){
        compute = [](int y){ return y*y; };
      }
      else if (a == 1){
        compute = [](int y){ return 2*y; };
      }
      else{
        compute = [](int y){ return y; };
      }

    }

    
    std::function<int(int)> compute;
    
  private:
    int a;
};

// usage


int main()
{
 
    A myA(1); // private variables set only once
    std::cout << myA.compute(10) << std::endl;
    std::cout << myA.compute(1) << std::endl;
    return 0;
}

推荐阅读