开发者

Nested function alternatives in C++

开发者 https://www.devze.com 2023-03-23 22:10 出处:网络
I want to make a function f() that uses three values to compute its result: a, b, and e. e is dependent on a and b, so technically f() is only a function of a and b. But for the sake of readability, i

I want to make a function f() that uses three values to compute its result: a, b, and e. e is dependent on a and b, so technically f() is only a function of a and b. But for the sake of readability, it is easier to look at a function containing the abstraction e than to look at a messier formula containing many a's and b's.

Is there any way to use dependent variables like e with开发者_开发技巧out the use of nested functions, which C++ does not allow?


C++ does have local variables, which makes this easy:

double f(double const a, double const b)
{
    double const e = a * b + b * b * b;
    return a + b + e;
}


You can write a local struct which can define a static function, which can be used as if its nested function as:

int f(int a, int b)
{
   struct local
   {
        static int f(int a, int b, int e)
        {
             return e * (a + b);
        }
   };
   return local::f(a,b, a*b);
}


Not sure I understand your question, but if you're just after a way to make your function more readable by introducing a dependent variable, why not just calculate that variable in a separate function called by your main function:

float CalculateE(float a, float b)
{
    return (a + b);
}

float f(float a, float b)
{
    float e = CalculateE(a, b);
    return a + b + e;
}


What's wrong with:

int compute_e(int a, int b)
{
    return whatever;
}

int func(int a, int b)
{
    int e = compute_e(a, b);
}


You can do this:

int f(int a, int b)
{
    struct LocalFunc
    {
        int operator()(int a, int b)
        {
            return a*b + b*b*b;
        }
    };
    LocalFunc e;
    return e(a,b)*a+b;
}


I think that you can write some notes.

int FuncSum(int a, int b)
{
    //return the sum of a + b
    return a + b ;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消