Spread operator in several languages vs C++ parameter packs

2,242 views
Skip to first unread message

Mike Austin

unread,
Apr 1, 2017, 8:13:37 PM4/1/17
to PiLuD
Some languages (Ruby, Groovy, new JS) have a spread operator that expands an array into function arguments, or into another array. C++ has parameter packs, which are similar, but can spread an expression instead of just a value.

Example:

// JavaScript spread operator

function foo(...args) {
 
return ["foo", ...arg.map(arg => arg.toString()];
}

// C++ parameter packs

template<typename ...T>
void foo(T&... arg) {

 
return array(arg.toString()...);

}

Parameter packs allow you to spread an expression, which is pretty nifty, but if you just want to iterate over the values you need to use index_sequence to simulate indicies using template recursion. [wipes forehead] :)

It might be nice to support both spread expressions and regular iteration over parameters. Maybe something like this:


// Spread expression

function foo(args...) {
 
return ["foo", args.toString().toUpper()...];
}

// Spread iterable

function foo(args...) {
 
return "foo" ++ args.map(arg => arg.toString().toUpper());
}

Groovy has a spread-dot operator which is kind of handy, but only works for one method, not an expression:

// Groovy spread-dot operator

args
*.toString()

I prefer postfix "...", but JavaScript ES6 uses prefix. It's also more compatible with TypeScript's parameter tyiping. E.g "function foo(...args: Number[]) {}". "..." on the other side would make "args...:", which is kind of odd looking.

Mike

Reply all
Reply to author
Forward
0 new messages