I have an unknown type T that might be non-copy- or move-assignable, a function T op(const T &foo, Other bar) that computes and returns a new T based on an existing one, and a recursive function:
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);
}
The compiler can't always optimize the tail call, because T might have a non-trivial destructor. I'm trying to manually rewrite it with a loop, but can't figure out how to reassign to z.
T, then it must be copy or move constructible, so why would it not be copy or move assignable? I guess you will need to create a new object each time, maybe dynamically allocating it?Tisstd::unique_ptr<int>...? I want to do it on stack though, for better performance.typename Funtemplate parameter instead of explicitly usingstd::fuction. That way, also regular functions and lambdas will work.new/deleteinto a buffer you provide, that could live on the stack, withchar buffer[sizeof(T)];, but it'd be nasty. If you require copy construction, can you really not require copy assignment?