简体   繁体   English

函数指针作为非类型模板参数

[英]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. 我目前正在将GTK +移植到动态语言,其中的挑战之一就是将GTK +函数转换为语言绑定。 I attempt to use C++ templates to simplify it. 我尝试使用C ++模板来简化它。

For example, to convert 'gtk_widget_show_all' to dynamic language's 'show_all', I first define following generic function: 例如,要将“ gtk_widget_show_all”转换为动态语言的“ show_all”,我首先定义以下通用函数:

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: 然后,我可以很容易地将“ gtk_widget_show_all”绑定到“ show_all”:

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: 但是当GTK +函数变得更加复杂时,为每种类型的GTK +函数定义每个SimpleMethod就像这样:

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. Boost.Preprocessor将帮助您生成重载。 C++11 variadic template arguments should make this much easier. C ++ 11可变参数模板参数应使此操作更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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