Let's say I have a variable number of arguments that I want to propagate together. The first way that I think is a recursive algorithm:
template<typename Head> u64 Multiply(Head head) const { return head; } template<typename Head, typename... Tail> u64 Multiply(Head head, Tail... tail) const { return head * Multiply(tail...); }
But then I saw this trick:
// u32 and u64 are 32 and 64 bit unsigned integers. template<typename... T> u64 Multiply(T... args) { u64 res = 1; for (const u32& arg: {args...}) res *= arg; return res; }
The second seems to me nicer. Easier to read. However, how does this affect performance? Is anything copied? What does {args...} first? Is there a better way?
I have access to C ++ 14.
Edit to be clear: this is about multiplying runtime, not compilation time.
More to be clear: I do not want to compute integers necessarily (although this is my current application), but the algorithm I found was specialized for integers.
Optional: Arguments of the same type. Algorithms without this restriction would be very interesting, but perhaps for another question.
c ++ templates c ++ 14
Aart stuurman
source share