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

Function pointer as non-type template parameter

本文关键字:参数 类型 指针 函数      更新时间:2023-10-16

我目前正在将GTK+移植到一种动态语言中,其中一个挑战是将GTK+函数转换为语言绑定。我尝试使用c++模板来简化它。

例如,要将'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 (); 
}

然后我可以很容易地将'gtk_widget_show_all'绑定到'show_all':

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

但是当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) {
    ...
}

它会变得相当恶心。有没有什么好办法把这些函数简化成一个函数?

您可以根据参数的数量定义多个重载,如下所示:

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...

提振。预处理器将帮助您生成过载。c++ 11可变模板参数应该会使这更容易。