简体   繁体   English

使用函数对象进行C ++代码重构

[英]c++ code refactoring using function objects

I have some functionality that returns a value based on values that are set once at start up (in constructor). 我有一些功能可以基于启动时(在构造函数中)设置一次的值返回一个值。 As these conditional value are only set once, I dont want to be checking them all the time. 由于这些条件值仅设置一次,因此我不想一直检查它们。 Is there a way to do the if-check only once and then dont do it again and again using function objects or some other mechanism? 有没有一种方法可以只执行一次if-check,然后不使用函数对象或其他某种机制来一次又一次地执行if-check?

class MyValue {
    bool myVal; //set only once in the constructor
    int myval1; //often updates
    int myval2; //often updates


    myValue(bool val, int val1, int val2)
    {
        myVal = val; // only place where myVal is set

        // this value changes often in other functions not shown here
        myval1 = val1;

        // this value changes often in other functions not shown here
        myval2 = val2;
    }

    int GetMyValue() //often called
    {
        if(myval)    /* Is there a way I dont have to do an if check here? 
                        and simply write a return statement? */
            return myval1;

        return myval2;
    }    
};

Use a pointer: 使用指针:

class MyValue
{
   int* myVal;
   int myval1; //often updates
   int myval2; //often updates

  myValue(bool val, int val1, int val2)
  {
     if (val) { 
         myVal = &myval1; 
     } else { 
         myVal = &myval2 
     }
     myval1 = val1;
     myval2 = val2;
  }

  int GetMyValue() //often called
  {
     return *myval;
  }

};

(or even better a reference as in Rabbid76 answer) (或者甚至更好的参考,如在Rabbid76答案中)

Use a member which is either a reference to myval1 or to myval2 , the referenc has to be initialized once in the constructor: 使用一个部件,其可以是一个参考myval1myval2 ,中借鉴必须在构造函数一旦被初始化:

class MyValue
{
    bool myVal; //set only once in the constructor
    int myval1; //often updates
    int myval2; //often updates
    int &valref;

public:
    MyValue( bool val, int val1, int val2 )
        : myVal( val )
        , myval1( val1 )
        , myval2( val2 )
        , valref( val ? myval1 : myval2 )
    {}

    int GetMyVal() { return valref; }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM