Skip to content

std::variant and JS null #66

@reubenscratton

Description

@reubenscratton

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions