简体   繁体   中英

Function pointer as non-type template parameter

I'm currently porting GTK+ to a dynamic language, one of the challenge is to convert GTK+ functions to language bindings. I attempt to use C++ templates to simplify it.

For example, to convert 'gtk_widget_show_all' to dynamic language's 'show_all', I first define following generic function:

template<class Type, class GtkType, void function (GtkType*)>
static Handle<Value> SimpleMethod (const Arguments& args) {
    GtkType *obj = blablabla...;

    function (obj);

    return Undefined (); 
}

Then I can bind the 'gtk_widget_show_all' to 'show_all' very easily:

NODE_SET_PROTOTYPE_METHOD (constructor_template, "show_all", (SimpleMethod<Widget, GtkWidget, gtk_widget_show_all>));

But when the GTK+ function becomes more complex, It would be a hell for defining every SimpleMethod for every type of GTK+ function, like this:

template<class Type, class GtkType, void function (GtkType*, const char *)>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

template<class Type, class GtkType, void function (GtkType*, int)>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

template<class Type, class GtkType, int function (GtkType*)>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

template<class Type, class GtkType, void function (GtkType*, const char *, const char *)>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

It will become rather disgusting. Is there a good way to simplify those functions to one function?

You can define a number of overloads, based on the number of arguments, like this:

template<class Type, class GtkType, class ReturnType, ReturnType function ()>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

template<class Type, class GtkType, class ReturnType, class Arg0, ReturnType function( Arg0 )>
static Handle<Value> SimpleMethod (const Arguments& args) {
    ...
}

...and so on...

Boost.Preprocessor would help you generate the overloads. C++11 variadic template arguments should make this much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM