C++用函数替换代码的最佳方法

Jea*_*Luc 1 c++ for-loop function c++11

如果我有这样的功能:

void Func(T a)
{
    T b, c, d;
    for (uint i = 0; i < 10000; ++i)
    {
        b = Call1(a);
        c = Call2(b);
        d = Call3(c);
    }
}
Run Code Online (Sandbox Code Playgroud)

我基本上只是想使函数看起来像形式:

void Func(T a)
{
    T d;
    for (uint i = 0; i < 10000; ++i)
        d = Call(a);
}
Run Code Online (Sandbox Code Playgroud)

Call是这样的:

T Call(T a)
{
    T b, c;
    b = Call1(a);
    c = Call2(b);
    d = Call3(c);
    return d;
}
Run Code Online (Sandbox Code Playgroud)

是否Call必须重新初始化b并且c每次在循环中调用它?我应该,也许,使用static T b, c而不是在Call function

R S*_*ahu 5

您询问:

每次在循环中调用时,调用是否必须重新初始化b和c?

答案是肯定的.

您询问:

或许,我应该在Call函数中使用静态T b,c吗?

答案是,很可能不是.

如果您担心创建实例的成本T,可以使用以下方法优化函数:

T Call(T a)
{
    return Call3(Call2(Call1(a)));
}
Run Code Online (Sandbox Code Playgroud)