4 ms·
Fold expressions are expanded entirely at compile time to create a fixed-size expression that gets compiled normally (the number of terms in any given case is k
by somebodynew 6y ago
Fold expressions are expanded entirely at compile time to create a fixed-size expression that gets compiled normally (the number of terms in any given case is known before machine code is generated). Applying a fold over a std::vector would require runtime iteration (see std::accumulate).
This is essentially a QoL improvement for existing users of variadic templates, where unnecessary complexity was required to simulate the behavior fold expressions provide for packs.
- uryga 6y agoi get that, i just think it'd be nice if they could be used for run-time stuff too – why create a gap between the compile- and run-time parts of the language? it seems like desugaring it into a loop should be pretty straightforward¹; it'd just be a concise replacement for some uses of std::accumulate. though as mentioned, i don't really use C++ much. are there reasons why this wouldn't work well for run-time stuff? --- ¹ it'd have to be mindful of short-circuiting constructs, but compilers special-case those anyway
- jfkebwjsbx 6y agoIt guess it would require a different syntax, otherwise it may not be clear how it was desugared (runtime vs. compile). Then again, we already have for loops, range for loops, the ranges library, the std algorithms, the parallel algorithms... I don't think people would welcome yet another way of writing things, but who knows...
- uryga 6y ago> otherwise it may not be clear how it was desugared (runtime vs. compile) but does that really matter, as long it has well-defined semantics? even for the compile-time case, it's up to the compiler/optimizer to decide whether `(xs + ...)` ends up as multiple ADDs or one ADD in a loop – you're only guaranteed that it's observable behavior will be `xs[0] + xs[1] + xs[2] + ...`, no?
- jfkebwjsbx 6y agoYes, it does matter. When you are programming in a language like C++, you want to understand what the compiler generates for a given abstraction.