Skip to content

Avoid extra memory allocation with templates #602

Closed
@dmitryash

Description

@dmitryash

I suppose that it is possible to add methods in the following way to avoid extra memory allocation:

Example:

template <class T> 
class ObjectWrap {
    using MethodType = Value (T::*)(const CallbackInfo &info);

    template <MethodType method>
    static auto ObjectWrap<T>::InstanceMethod2(const char* utf8name) -> ClassPropertyDescriptor<T>; 
};

template <typename T>
template <typename ObjectWrap<T>::MethodType method>
inline auto ObjectWrap<T>::InstanceMethod2(const char* utf8name) -> ClassPropertyDescriptor<T>  {
    napi_property_descriptor desc = {};
    desc.utf8name = utf8name;
    desc.method = [](napi_evn env, napi_callback_info args) {
        return details:;WrapCallback([&]{
            CallbackInfo cb_info(env, args);
            T* instance = Unwrap(cb_info.This().As<Object>());
            return (instance->*cb)(callbackInfo);
        });
    };
    return desc;
}

// How to use
class Test: public Napi::ObjectWrap<Test> {
public:
    static auto define_class(Napi::Env env) -> Napi::Function {
        return DefineClass(env, "Test", {
            InstanceMethod2<&Test::get_value>("get_value");
        });
    }

    auto get_value(const Napi::CallbackInfo &args) -> Napi::Value;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions