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

std::variant and JS null #66

Open
reubenscratton opened this issue Dec 20, 2023 · 2 comments
Open

std::variant and JS null #66

reubenscratton opened this issue Dec 20, 2023 · 2 comments

Comments

@reubenscratton
Copy link

First up let me say how much I love this project! It's embarrassingly better than my own feeble attempt to wrap C++ types for use with QuickJS, and I've learned several useful template meta-programming tricks from reading the source code.

I hit a snag when I tried to implement a C++ object property that could be set (in JS) to a string, or an integer, or null. Obviously I chose to implement this property as having type std::variant<std::string, int> on the C++ side. But how to represent null? I tried using void*, shared_ptr, optional... but couldn't get anything to work. RTFM'ing it seems std::monostate is the thing to use, i.e. my property type becomes std::variant<std::string, int, std::monostate>.

To get this to work I had to implement a js_traits that can wrap and unwrap std::monostate and also alter the existing js_traits<std::variant<...>>::unwrap() to use std::monostate when given a JS_NULL.

My question is: Have I done the right thing? Is this the best way to implement support for nullable property values?

@ftk
Copy link
Owner

ftk commented Dec 21, 2023

I think std::monostate is more similar to js undefined (because js variables are undefined when not initialized). For js null std::nullptr_t might be good choice.

For variant support, yes, you currently need to modify quickjspp.hpp to add new types

@ddevienne
Copy link

Just a quick comment to mention that std::variant default-constructs to its first type's default value.
Thus I think typically, std::monostate (or std::nullptr_t) should be your first rather than last type.
And @ftk , very good point about undefined ~= std::monostate and null ~= std::nullptr_t.

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

3 participants