Optional arguments
reubenscratton opened this issue · comments
I'm working on an implementation of the standard 'fetch' API for QuickJS. Like many other JS APIs,fetch
uses optional arguments. It would therefore be helpful if the code in quickjspp.hpp
that unwraps JS arguments for C++ functions could tolerate undefined/optional values rather than throwing an exception, e.g. something like this:
@@ -568,7 +568,5 @@
{
if (size_t(argc) <= I) {
- JS_ThrowTypeError(ctx, "Expected at least %lu arguments but received %d",
- (unsigned long)NArgs, argc);
- throw exception{ctx};
+ return js_traits<std::decay_t<T>>::unwrap(ctx, JS_UNDEFINED);
}
return js_traits<std::decay_t<T>>::unwrap(ctx, argv[I]);
I.e. the type T
can be a std::optional
or some other type whose js_traits
can convert to and from 'undefined'.
Would this be a good idea? What have I not thought of?
Good idea!
Another idea is to create a specialization for std::optional
template <typename T, size_t I, size_t NArgs>
struct unwrap_arg_impl<std::optional<T>, I, NArgs> {
static std::optional<T> unwrap(JSContext * ctx, int argc, JSValueConst * argv) {
if (size_t(argc) <= I) return std::nullopt;
return {js_traits<std::decay_t<T>>::unwrap(ctx, argv[I])};
}
};