开发者

Function pointer as non-type template parameter

开发者 https://www.devze.com 2023-04-12 04:22 出处:网络
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.

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 (con开发者_高级运维st 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消