How can I have a function of type (arr: T[]) => T in C++ that compile to WebAssembly?

267 Views Asked by At

I would like to write a function head that return the first value of a an array with a type signature (arr: T[]) => T (Typescript pseudo code).

The idea is to compile the C++ function to WebAssembly using Emscripten and use this head function in my javascript app.

I know C++ template would provide the right tool for such an abstraction but I wonder if templates would work as they operate at compile time.

PS: I am a C++ beginner, any link to any ressource is welcome, I would like to learn.

1

There are 1 best solutions below

0
On BEST ANSWER

WebAssembly doesn't support "generics" or "templates" per-se, it only has types i32, i64, f32, and f64.

In pure C++ that's fine because your compile will just instantiate all the template specializations you need, and then use them within WebAssembly. If you inter-operate across languages (say C++ in WebAssembly to JavaScript or TypeScript) then you can explicitly specialize your templates and export them from your .wasm file so that JavaScript / TypeScript can call that specialization. Of course that means you have to know what you'll need up front!

One thing you could do, but is totally impractical, is just-in-time generate the .wasm file at runtime when you figure out what template instantiation you actually need. That's impractical because tooling just isn't there right now, you'd need at least parts of a C++ compiler running in WebAssembly, and then you'd need to patch your WebAssembly.Table at runtime (which is totally doable... just not actively done these days).

For your specific usecase though (return the first element of an array) I'm not sure you can do much! Because WebAssembly's types are so limited you can only deal with things that fit in 32 or 64 bits if you must pass through as parameters. Even then, your array can't just generically expand to arguments because WebAssembly parameter counts are pre-determined at compilation time (binding them to JavaScript can drop / getValue on them, but you really don't want that). What you want is probably to pass things through the Memory, which is similar to dealing with strings (in that strings are an array of characters).