I'm creating a C++ class that handle the values passed by the client in a JSON (converted in a dict with json.loads), I make a Cpp class named Parameter and I need to pass a type to the constructor to specify the cast needed, but I don't know how to use this type (in Python is like return type_parameter(value))
I also need to convert string values to datetime object like '2024-10-10' and this is the reason for the format parameter, please let me know also how to make this thing
#include <nanobind/nanobind.h> #include <nanobind/stl/string.h> #include <string> #include <utility> namespace nb = nanobind; using namespace nb::literals; class Parameter { private: std::string name; nb::object value; [[nodiscard]] nb::object _get_value( const nb::dict& source, const bool& required, const nb::type_object& type_, const nb::object& default_, const std::string& format ) const { if (required and !source.contains(name.c_str())) throw std::domain_error("Parameter " + name + " is required"); return convert(source.contains(name.c_str()) ? source[name.c_str()] : default_, type_, format); } [[nodiscard]] static nb::object convert( const nb::object& value, const nb::type_object& type_, const std::string& format ) { if (value.is_none() or type_.is_none()) return value; return value; } public: Parameter( std::string name_, const nb::dict& source, const nb::type_object& type_, const bool& required = false, const nb::object& default_ = nb::none(), const std::string& format = "", const nb::object& check = nb::none() ) : name(std::move(name_)) { value = _get_value(source, required, type_, default_, format); if (!check.is_none()) check(value); } [[nodiscard]] nb::object getValue() const { return value; } [[nodiscard]] std::string getName() const { return name; } }; NB_MODULE(Test3, m) { nb::class_<Parameter>(m, "Parameter") .def(nb::init< std::string, const nb::dict&, const nb::type_object&, const bool&, const nb::object&, const std::string&, const nb::object&>(), "name"_a, "source"_a, "type_"_a, "required"_a = false, "default"_a = nb::none(), "format_"_a = "", "check"_a = nb::none() ) .def("get_value", &Parameter::getValue) .def("get_name", &Parameter::getName); } I'm expeting to pass this parameter and use it to cast the value find in source.
(ps: correct me for anything other than the main question, I'm learning just now how cpp binding works)