Skip to content

Overloaded functions binding

Pavel Medvedev edited this page May 14, 2015 · 1 revision

Currently there is no ability to bind into v8pp a set of overloaded C++ functions with the same name. The solution is to use generic v8::FunctionCallback in order to dispatch appropriate function overloading from there:

void fun(int = 0);
void fun(float, float);
void fun(std::string const&);

void fun_v8(v8::FunctionCallbackInfo<v8::Value> const& args)
{
    switch (args.Length())
    {
    case 0:
        return fun();
    case 1:
        if (args[0]->IsInt32())
        {
            return fun(v8pp::from_v8<int>(args[0]));
        }
        else if (args[0]->IsString())
        {
            return fun(v8pp::from_v8<std::string>(args[0]));
        }
        break;
    case 2:
        if (args[0]->IsNumber() && args[1]->IsNumber())
        {
            return fun(v8pp::from_v8<float>(args[0]), v8pp::from_v8<float>(args[1]));
        }
        break;
    }
    throw std::invalid_argument("invalid fun arguments");
}

Dispatching for overloaded class constructors can be managed the same way, either with v8pp::factory specialization:

class Some
{
public:
   Some();
   Some(int);
   Some(std::string);
};

namespace v8pp {

template<>
struct factory<Some>
{
	static Some* create(v8::FunctionCallbackInfo<v8::Value> const& args)
	{
		if (args.Length() == 0) return new Some;
		if (args[0]->IsNumber()) return new Some(from_v8<int>(args[0]));
		if (args.[0]->IsString()) return new Some(from_v8<std::string>(args[0]));

		return nullptr;
	}

	static void destroy(v8::Isolate*, Some* object)
	{
		delete object;
	}
};

} // v8pp

Binding for such class should have .ctor signature, as the factory::make:

void init_bindings(v8::Isolate* isolate)
{
    v8pp::class_<Some> some_class(isolate);
    some_class.ctor<v8::FunctionCallbackInfo<v8::Value> const&>();
    // ... other Some class bindings
}

More examples in test_factory.cpp

Clone this wiki locally