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

标签 c++ function c++11 for-loop

如果我有这样的功能:

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

我基本上只是想让这个函数看起来像这样:

void Func(T a)
{
    T d;
    for (uint i = 0; i < 10000; ++i)
        d = Call(a);
}

Call 是这样的:

T Call(T a)
{
    T b, c;
    b = Call1(a);
    c = Call2(b);
    d = Call3(c);
    return d;
}

每次在循环中调用时,Call 是否都必须重新初始化 bc?也许,我应该在 Call 函数 中使用 static T b, c 吗?

最佳答案

你问:

Is Call going to have to reinitialise b and c everytime it is called in the loop?

答案是肯定的。

你问:

Should I, perhaps, use static T b, c instead in the Call function?

答案是,很可能不会。

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

T Call(T a)
{
    return Call3(Call2(Call1(a)));
}

关于C++ 用函数替换代码的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709639/

相关文章:

java - "You must enter a password with at least one number a lower case and a symbol"

javascript - 计算 Javascript 中的参数

c++ - 我怎样才能清楚地指定我要传递哪些参数以及哪些参数保持默认?

c++ - 单元测试应用程序到硬件的接口(interface)——模拟与否

c++ - 使用 stackBefore 更改 QGraphicsItem 堆栈顺序

c++ - 从第三方类实现虚函数

c++ - 使用指针的合法遗留代码突然变成了 UB

c++ - 这种替代的 'for' 循环语法有什么依据吗?

c++ - 没有模板的 ADL

c++ - 使用 g++8 和 c++20 的 std::async 的编译问题