Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional arguments #67

Open
reubenscratton opened this issue Jan 14, 2024 · 2 comments
Open

Optional arguments #67

reubenscratton opened this issue Jan 14, 2024 · 2 comments

Comments

@reubenscratton
Copy link

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?

@ftk
Copy link
Owner

ftk commented Jan 15, 2024

Good idea!

@ftk
Copy link
Owner

ftk commented Jan 17, 2024

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])};
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants