将递归转换为循环

Ziz*_*Tai 3 c++ optimization recursion

我有一个未知类型T,可能是非copy-或move-assignable,一个基于现有函数T op(const T &foo, Other bar)计算和返回new T的函数,以及一个递归函数:

template<typename Iter, typename T>
T foldLeft(Iter first, Iter last, const T &z, std::function<T(T, Other)> op)
{
    if (first == last) {
        return z;
    }
    return foldLeft(std::next(first), last, op(z, *first), op);
}
Run Code Online (Sandbox Code Playgroud)

编译器不能总是优化尾调用,因为T可能有一个非平凡的析构函数.我试图用循环手动重写它,但无法弄清楚如何重新分配z.

Jar*_*d42 5

您可以执行以下操作,但限制很奇怪,使用std::accumulate似乎更简单

template<typename Iter, typename T, typename Fn>
T foldLeft(Iter first, Iter last, const T &z, Fn op)
{
    std::aligned_storage_t<sizeof (T), alignof (T)> buf;
    T* res = new (&buf) T(z);
    for (auto it = first; it != last; ++it) {
        auto&& res2 = op(res, it);
        res->~T();
        res = new (&buf) T(std::move(res2));
    }
    T final_res = *res;
    res->~T();
    return final_res;
}
Run Code Online (Sandbox Code Playgroud)

请注意,它不是例外安全的.