2011-10-12 121 views
1

我目前正在将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 +的功能变得更加复杂,这将是确定每SimpleMethod对每种类型GTK +的功能,这样的地狱:

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

它会变得相当恶心。有没有将这些功能简化为一种功能的好方法?

+0

如果您使用C++,为什么不使用GTK + [gtkmm](http://www.gtkmm.org/en/)的现有C++包装器? –

+0

@ another.anon.coward GTK +被设计为绑定到其他语言,而gtkmm增加了许多C++功能,但在移植到动态语言时没有用处。 – fool

回答

0

您可以定义多个重载,根据参数的数目,这样的:

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会帮助你产生过载。 C++ 11 variadic模板参数应该使这更容易。

+0

你的想法很好,但是可以使用C++ 11 variadic模板参数来生成任意的长函数调用,比如'function(Arg0,Arg1,...)'? – fool

+0

@fool:我相信它可能带有一些额外的模板魔法,但是我的编译器还不支持它们,所以我不知道。 –

相关问题