这是一个令人尴尬的问题,在这个题目上很难想到任何明智的东西。也许我可以回顾一下..。
我正在处理以下代码:
static FinalClass* final_class( PyObject* o ) {/*...*/}
template< F0 f >
static PyObject* handler( PyObject* o, PyObject* )
{
try
{
Object result{ (final_class(o) ->* f)() };
return new_reference_to( result.ptr() );
}
catch( Exception & )
{
DBG_LINE( "! ! ! Exception Python calling new-style-class handler ! ! !" );
return 0;
}
}
template< F1 f >
static PyObject* handler( PyObject* o, PyObject* _a )
{
try
{
Object result{ (final_class(o) ->* f)(Tuple{_a}) };
return new_reference_to( result.ptr() );
}
catch( Exception & )
{
DBG_LINE( "! ! ! Exception Python calling new-style-class handler ! ! !" );
return 0;
}
}
template< F2 f >
static PyObject* handler( PyObject* o, PyObject* _a, PyObject* _k )
{
try
{
Object result{ (final_class(o) ->* f)(Tuple{_a}, Dict{_k}) };
return new_reference_to( result.ptr() );
}
catch( Exception & )
{
DBG_LINE( "! ! ! Exception Python calling new-style-class handler ! ! !" );
return 0;
}
}可以看出,这三种情况中的每一种都有相同的模式。
在第三种情况下,函数签名还有一个额外的参数,尽管实验表明,如果需要的话,我可以在前两种情况中添加一个虚拟参数。
除了使用#define之外,我看不出任何可能的抽象机制的方法。
有什么事要做吗?
发布于 2014-11-15 03:31:18
唯一能想到的就是这样的事情:
template<typename functor_type, typename default_value_functor>
auto execute_and_catch(functor_type &&functor,
default_value_functor &&default_value)
-> decltype(functor())
{
try
{
return functor();
}
catch( Exception & )
{
DBG_LINE( "! ! ! Exception Python calling new-style-class handler ! ! !" );
return default_value();
}
}然后,您将如何使用它的一个例子:
template< F0 f >
static PyObject* handler( PyObject* o, PyObject* )
{
execute_and_catch([&]
{
Object result{ (final_class(o) ->* f)() };
return new_reference_to( result.ptr() );
},
[]
{
return 0;
});
}其他的例子也会发生类似的变化。
当然,这仍然会导致大量的模板膨胀;但是至少源代码将是紧凑的,紧凑的。
发布于 2014-11-15 04:11:58
也许您可以使用variadic templates做一些事情,前提是Tuple有一个构造函数可以将PyObject*作为输入,例如:
template< typename F, typename... Params >
static PyObject* handler( F f, PyObject* o, Params... p )
{
try
{
Object result{ (final_class(o) ->* f)(p...) };
return new_reference_to( result.ptr() );
}
catch( Exception & )
{
DBG_LINE( "! ! ! Exception Python calling new-style-class handler ! ! !" );
return 0;
}
}
PyObject* h = handler(&someF0method, o);
PyObject* h = handler(&someF1method, o, a);
PyObject* h = handler(&someF2method, o, a, b);https://stackoverflow.com/questions/26941960
复制相似问题